文件的上传和下载 文件的下载 总结:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* 上传文件
*/
public void upload(MultipartFile excelFile,String fileName ) throws Exception {
InputStream stream = null;
OutputStream bos = null;
try {
stream = excelFile.getInputStream();// 把文件读入
bos = new FileOutputStream(fileName);

int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, bytesRead);// 将文件写入服务器
}
}catch(Exception e) {
e.printStackTrace();
log.error(e.getMessage());
} finally {
try {
if(stream != null) {
stream.close();
}
if(bos != null) {
bos.close();
}
}catch(Exception e) {
e.printStackTrace();
log.error(e.getMessage());
throw new Exception(e);
}
}

}

文件的下载

1
2
3
4
5
6
7
8
9
10
11
@RequestMapping(value="/contentImport/downloadTktExpressTemplate.do")
public ResponseEntity<byte[]> downloadTktExpressTemplate(HttpServletRequest request) throws IOException {
String path = request.getSession().getServletContext().getRealPath("/res/template/快递数据.xls");
File file = new File(path);
String fileName = file.getName();
String dfileName = new String(fileName.getBytes("gb2312"), "iso8859-1");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", dfileName);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
}

总结:

文件上传和下载是项目中常用的功能,可以整理以后直接拿来用