• 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();
    }
    }
    }

    海纳百川 有容乃大 壁立千仞 无欲则刚
  • 相关阅读:
    Spring整合hibernate4:事务管理
    eclipse添加约束文件
    转]@SuppressWarnings 详解
    spring + springMVC +hibernate 配置2
    spring +spring+ hibernate配置1
    eclipse下 hibernate逆向数据库操作示例!!
    Spring+hibernate 配置实例
    dubbo接口快速测试技巧
    Spring Boot Starter列表
    Spring Boot Starters是什么?
  • 原文地址:https://www.cnblogs.com/luchangyou/p/5857296.html
Copyright © 2020-2023  润新知