文档需要修复原因:因为此处错误代码是每次读取1024个字节都写入1024个字节,但是不可能每次都读取到1024个字节,这里却每次都写入1024个字节,虽然文档修复后没有什么缺少,但是用代码去解析文档的时候去会造成问题。
byte[] bts = new byte[1024];
// 一个一个字节的读取并写入
while (is.read(bts) != -1) {
os.write(bts);
}
正确代码
每次读多少字节就写多少字节即可。
byte[] bts = new byte[1024];
int len = 0;
while((len = is.read(bts)) >0){
os.write(bts, 0, len);
}
完成代码
@RequestMapping("fileUpload")
@ResponseBody
public Map fileUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request)
throws IOException {
Map map = new HashMap<>();
try {
String path = request.getSession().getServletContext().getRealPath("/") + file.getOriginalFilename();
// 获取输出流
OutputStream os = new FileOutputStream(path);
// 获取输入流 CommonsMultipartFile 中可以直接得到文件的流
InputStream is = file.getInputStream();
byte[] bts = new byte[1024];
// 一个一个字节的读取并写入
int len = 0;
while((len = is.read(bts)) >0){
os.write(bts, 0, len);
}
os.flush();
os.close();
is.close();
map.put("success", true);
} catch (FileNotFoundException e) {
e.printStackTrace();
map.put("success", false);
}
return map;
}



