spring mvc 实现文件上传下载

时间:2023-03-08 16:53:39
spring mvc 实现文件上传下载

/**
* 文件上传
* @param pictureFile
*/
@RequestMapping("/reportupload")
public ResponseInfo uploadImg(MultipartFile pictureFile){

  //如果用的是Tomcat服务器,则文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\upload\\文件夹中
  String realPath = request.getSession().getServletContext().getRealPath("/upload/");
  //这里不必处理IO流关闭的问题,因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉,我是看它的源码才知道的
  try {
    FileUtils.copyInputStreamToFile(pictureFile.getInputStream(), new File(realPath, pictureFile.getOriginalFilename()));
  } catch (IOException e) {
    e.printStackTrace();
  }
}

/**
* 文件下载
* @param fileName
* @param request
* @param response
* @return
*/
@RequestMapping("/download")
public void download(String fileName, HttpServletRequest request,
HttpServletResponse response) {
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;fileName="
+ fileName);
OutputStream os = null;
try {
String realPath = request.getSession().getServletContext().getRealPath("/upload");
InputStream inputStream = new FileInputStream(new File(realPath
+ File.separator + fileName));

os = response.getOutputStream();
byte[] b = new byte[2048];
int length = 0;
while ((length = inputStream.read(b)) != -1) {
os.write(b, 0, length);
}

// 这里主要关闭。
inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(os != null){
os.close();
}
}catch (IOException e) {
e.printStackTrace();
}
try {
if (os != null)
os.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}