zoukankan      html  css  js  c++  java
  • 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();
    }
    }
    }

    海纳百川 有容乃大 壁立千仞 无欲则刚
  • 相关阅读:
    TX1/TX2 Qt安装与配置
    Gsteramer 环境配置
    NVIDIA Jetson TX2刷机
    TX2之多线程读取视频及深度学习推理
    搭建USB摄像头转RTSP服务器的多种方法
    TX2 五种功耗模式
    NVIDIA TX1/TX2 对比
    tf.reduce_mean
    关闭tensorflow运行时的警告信息
    sudo: /usr/bin/sudo must be owned by uid 0 and have the setuid bit set
  • 原文地址:https://www.cnblogs.com/luchangyou/p/5857296.html
Copyright © 2011-2022 走看看