When the author wrote an interface to download files from aliyun server in the form of attachments in the project, he encountered a problem, and there was no relevant solution in online search. Finally, he realized the download function by consulting API documents and combining his own experience.

By querying the oss official document, I found that only a download file to the local method (method 1), but this method downloaded files can only download the file to the local directory of a fixed, which must be written in API provides methods to death the downloaded file download path, download and download the file without any hint, Therefore, this method is not suitable for direct use in projects.

/** * Download files from Aliyun (download directory is fixed, cannot be changed) *@param map
 * @return* /
 // Endpoint This section uses Hangzhou as an example. Enter other regions based on actual conditions
 String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
 // accessKey can be viewed at https://ak-console.aliyun.com/#/
 String accessKeyId = "<yourAccessKeyId>";
 String accessKeySecret = "<yourAccessKeySecret>";
 String bucketName = "<yourBucketName>";
 // Create an OSSClient instance
 OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
 New File("
      
       ") This File object needs to be given a local directory to which the File will be downloaded
      
 ossClient.getObject(new GetObjectRequest(bucketName, "<yourKey>"), new File("<yourLocalFile>"));
 / / close the client
 ossClient.shutdown();
Copy the code

Finally, through API documentation, we found:

Download in the “plate” first “in the form of flow” download file approach, “ossObject. GetObjectContent ()” method can get id of the specified file and returns a byte stream, so can use this feature, a method of transformation of their (method 2) :

/** * Download files from Aliyun (as attachments) *@param request
 * @param response
 */
@ResponseBody
@RequestMapping(value = "/download", method = RequestMethod.GET)
public void downLoadFile(HttpServletRequest request,HttpServletResponse response){
	try {
		String objectKey = request.getParameter("objectKey").toString();// Every file uploaded to Aliyun will have a unique objectKey value
		String filename =request.getParameter("filename").toString();// Get the name of the file to download from the foreground
		int i=filename.lastIndexOf("\ \");
		filename=filename.substring(i+1);
		String aliyunId = ApplicationPropertyUtils.getContextProperty("ALIYUN_ACCESS_KEY_ID");
		String aliyunSecret = ApplicationPropertyUtils.getContextProperty("ALIYUN_ACCESS_KEY_SECRET");
		String ossEndpoint =  ApplicationPropertyUtils.getContextProperty("ALIYUN_OSS_ENDPOINT");
		OSSClient ossClient  = new OSSClient(ossEndpoint, aliyunId, aliyunSecret);
		// Get the file object on Aliyun corresponding to fileID
		OSSObject ossObject = ossClient.getObject(bucketName, objectKey);//bucketName needs to be set yourself
		
		// Return after reading Object
		BufferedInputStream in=new BufferedInputStream(ossObject.getObjectContent());
		//System.out.println(ossObject.getObjectContent().toString());
		
		BufferedOutputStream out=new BufferedOutputStream(response.getOutputStream());
		// Notify the browser to download it as an attachment
		response.setHeader("Content-Disposition"."attachment; filename="+URLEncoder.encode(filename,"utf-8"));
		//BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream(new File("f:\\a.txt")));
		
		byte[] car=new byte[1024];
		int L=0;
		while((L=in.read(car))! = -1){
			out.write(car, 0,L);
			
		}
		if(out! =null){
			out.flush();
			out.close();
		}
		if(in! =null){
			in.close();
		}
		
		ossClient.shutdown();
		
	} catch(Exception e) { e.printStackTrace(); }}Copy the code

The above code to achieve a user – defined file download path, and successful download file method!

– note:

In the process of actually using this method to download, there may be a problem that the server does not report an error, but the file cannot be downloaded. It may be that the way the front-end page sends the download request is wrong, and it must be a GET request, and I do not know why, can not use AJAX GET method to access the change method. The method I use is window.location.href, but there may be other ways to access it, which I won’t explain here.

— About batch downloading files on Ali Cloud

This blog post realizes the method of downloading a single file from Ali cloud. Since there will be someone who needs to download multiple files from Ali cloud, students who need this blog can combine with my other blog

Zip in Java saves multiple files

The idea is: first get the file stream of all the files to be downloaded from Ali Cloud, and compress it into a compressed file stream through Java Zip, and then directly use the compressed file stream as the input stream of the download file to achieve multiple file download.