public void download(HttpServletResponse response, String fileName, String businessName, String filedir1) throws IOException { try { filedir = filedir1; OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret); //获取fileid对应的阿里云上的文件对象 OSSObject ossObject = getOssClient().getObject(bucketName, filedir + fileName); // 读去Object内容 返回 BufferedInputStream in = new BufferedInputStream(ossObject.getObjectContent()); BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream()); //通知浏览器以附件形式下载 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(); } }
阿里云OSS文件下载设置正确,不报错也无法下载文件
1.必须是get请求
2.必须是同步请求
所以在
@RequestMapping(value = "/downloadTemplate",method = RequestMethod.GET)
时必须使用上面的写法
不要使用ajax异步请求,而且在ajax中设置为get是不管用的
使用
window.open("/fileUpload/downloadTemplate?fileName="+$('#template').val(),'top');
如此来请求即可.