oss文件下载

@RequestMapping(value = "/downFile")
	@ResponseBody
	public void downFile(HttpServletRequest request, HttpServletResponse response) {
		BufferedInputStream input = null;
		OutputStream outputStream = null;
		try {
            String filePath = request.getParameter("path");
            filePath = filePath.replaceAll("\\\\", "/");
            String fileName = getName(filePath);

            response.reset();
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/x-msdownload");
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"),"ISO8859-1"));
            // endpoint,accessKeyId,accessKeySecret,bucketName是oss自带参数,登陆oss查看,或者给公司要,fileName是文件上传到oss后的文件名
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            OSSObject object = ossClient.getObject(bucketName, fileName);
            input = new BufferedInputStream(object.getObjectContent());
            byte[] buffBytes = new byte[1024];        
            outputStream = response.getOutputStream();          
            int read = 0;
            while ((read = input.read(buffBytes)) != -1) {
                 outputStream.write(buffBytes, 0, read);
            }     
            outputStream.flush();
            ossClient.shutdown();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
            	if (outputStream != null) {
            		outputStream.close();
            	}
            	if (input != null) {
            		input.close();
            	}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
	}
	
	// 获取添加后的文件名称
	public String getName(String filepath) {
		if (!filepath.equals(null)) {
			if (filepath.contains("/")) {
				return filepath.substring(filepath.lastIndexOf("/") + 1);
			}
		}
		return "";
	}

 

你可能感兴趣的:(java技术文档,oss,下载)