作者:纪筱陌_ | 来源:互联网 | 2023-09-10 12:45
背景
写了一个根据文件名下载文件的的方法(主要用来下载文件)
代码:
@ResponseBody@RequestMapping(value = "/downloadPhoto/{fileN}")public String downloadPhoto(@PathVariable String fileN,HttpServletRequest request,HttpServletResponse response) throws IOException {String fileName = fileN;if(fileName!=null){String filePath = "E:/imagesFile/" + fileName;System.out.println(filePath);File file = new File(filePath);if(file.exists()){response.setContentType("application/force-download");response.addHeader("Content-Disposition","attachment;fileName="+fileName);byte[] buffer = new byte[1024];FileInputStream fis = null;BufferedInputStream bis = null;try{fis = new FileInputStream(file);bis = new BufferedInputStream(fis);OutputStream os = response.getOutputStream();int i = bis.read(buffer);while(i!=-1){System.out.println("读到内容了:"+i);os.write(buffer,0,i);i=bis.read(buffer);}return "download success";}catch(Exception e){e.printStackTrace();}finally{bis.close();fis.close();}}}return "failure";}
事故
这个方法一直用得好好得,直到昨天我上传了一张大小小于8.6k的图片之后,在图片服务器虽然能看到完整无损的图片,但是当我调上面的这个方法下载文件时,却发现这个图片无法正常打开,并且大小只有1k
![](https://img.php1.cn/3cd4a/94ce/a6e/865776f6fe3d5f59.jpeg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3BpYW5vX2RpYW5v,size_16,color_FFFFFF,t_70)
接着我觉得可能是这个下载不能支持太小的图片,然后我尝试上传大小小于8.6k的文件(包括 doc,xlsx,txt 类型),发现同样也打不开,除了txt能打开,但是txt中的内容中文显示乱码,如果是全英文就不会乱码,但是结尾会出现一个字符串 “download success” 。。
解决
我怀疑是下载文件的时候,当文件大小小于8.6k时,代码中的下面这句返回会写进文件内容中。。。导致文件内容被修改后无法被识别
return "download success";
然后我把上面的方法的返回类型改为void,然后删掉上面这句的代码,结果就正常了,能上传任意大小的文件了。。。
可为什么会这样呢。。输出不是由OutputStream 来完成的么,为什么 return 会插一脚。。。