1. 文件上传
public static void saveFile(MultipartFile multipartFile, String savepath, String fileName){
File file = new File(savepath);
if (!file.exists()){
file.mkdirs();
}
File files = new File(savepath, fileName);
try {
multipartFile.transferTo(files);
} catch (IOException e) {
e.printStackTrace();
}
}
2. 文件下载
public static void downLoadFile(HttpServletResponse response, String filePath) {
File file = new File(filePath);
if (!file.exists()) {
throw new RRException("文件不存在或已被删除");
}
FileInputStream fis = null;
BufferedOutputStream bos = null;
BufferedInputStream bis = null;
try {
response.setCharacterEncoding("utf-8");
response.setContentType("application/octet-stream;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment;FileName=" + URLEncoder.encode(file.getName(), "UTF-8"));
response.addHeader("Content-Length", "" + file.length());
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
bos = new BufferedOutputStream(response.getOutputStream());
int length;
byte[] buffer = new byte[1024];
while ((length = bis.read(buffer)) != -1) {
bos.write(buffer, 0, length);
bos.flush();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
if (bis != null) {
bis.close();
}
if (bos != null) {
bos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
response的contentType
application/xhtml+xml XHTML格式
application/xml XML数据格式
application/atom+xml Atom XML聚合格式
application/json JSON数据格式
application/pdf pdf格式
application/msword Word文档格式
application/octet-stream 二进制流数据(如常见的文件下载)
application/x-www-form-urlencoded : <form encType=””>中默认的encType,form表单数据被编码为key/value格式发送到服务器(表单默认的提交数据的格式)