六、springMVC文件上传下载

文件上传

apache 上传组件方案

单文件上传

  1. 添加依赖

    <!--apache组件文件上传-->
    <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.3</version>
    </dependency>
    
  2. 在springMVC当中要注册一个文件上传解析器

    <!--文件上传解析器
        id必须为multipartResolver,原因是源代码里面写死了这个名字
    -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--单个文件最大上传大小-->
        <property name="maxUploadSizePerFile" value="20000000"></property>
        <!--指定上传编码-->
        <property name="defaultEncoding" value="UTF-8"></property>
        <!--定义最大文件大小 总的,单位为bytes-->
        <property name="maxUploadSize" value="200000000"></property>
    </bean>
    
  3. 准备上传页面

    <form action="${ctx}/file/upload" method="post" enctype="multipart/form-data">
        文件:<input type="file" name="file">
        <input type="submit" value="提交">
    </form>
    
  4. 后台

    @Controller
    @RequestMapping("/file")
    public class FileController {
    
        /*在Windows下的路径分隔符(\)和在Linux下的路径分隔符(/)是不一样的,
            当直接使用绝对路径时,跨平台会报No Such file or diretory异常。
            File.separator能解决这个问题
        */
        private static String uploadPath = "E:" + File.separator;
    
        //入参就可以选择上传的文件
        @RequestMapping("/upload")
        public String upload(@RequestParam("file")MultipartFile multipartFile,Model model){
            //1、传到那里去 2、我传什么东西 3、传的细节
            System.out.println("uploadPath=" + uploadPath);
            //1、判断
            if(multipartFile != null && !multipartFile.isEmpty()){
                //不能为空
                //2、获取原始的文件名
                String originalFilename = multipartFile.getOriginalFilename();
                System.out.println(originalFilename);
    
                //3、先截取文件的文件名前缀,不带后缀
                String fileNamePrefix = originalFilename.substring(0,originalFilename.lastIndexOf("."));
    
                //4、加工处理文件名,将原文件名+时间戳
                String newFileNamePrefix = fileNamePrefix + new Date().getTime();
    
                //5、得到新文件名
                String newFileName = newFileNamePrefix + originalFilename.substring(originalFilename.lastIndexOf("."));
    
                //6、构建文件对象
                File file = new File(uploadPath + newFileName);
    
                //7、上传操作
                try {
                    multipartFile.transferTo(file);
                    model.addAttribute("fileName",newFileName);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return "uploadSuc";
        }
    }
    

多文件上传

@RequestMapping("/upload2")
public String upload2(@RequestParam("file")MultipartFile[] multipartFiles,Model model){

    List<String> fileNames = new ArrayList<>();

    if(multipartFiles != null && multipartFiles.length > 0){
        //遍历
        for(MultipartFile multipartFile : multipartFiles){
            //1、传到那里去 2、我传什么东西 3、传的细节
            System.out.println("uploadPath=" + uploadPath);
            //1、判断
            if(multipartFile != null && !multipartFile.isEmpty()){
                //不能为空
                //2、获取原始的文件名
                String originalFilename = multipartFile.getOriginalFilename();
                System.out.println(originalFilename);

                //3、先截取文件的文件名前缀,不带后缀
                String fileNamePrefix = originalFilename.substring(0,originalFilename.lastIndexOf("."));

                //4、加工处理文件名,将原文件名+时间戳
                String newFileNamePrefix = fileNamePrefix + new Date().getTime();

                //5、得到新文件名
                String newFileName = newFileNamePrefix + originalFilename.substring(originalFilename.lastIndexOf("."));

                //6、构建文件对象
                File file = new File(uploadPath + newFileName);

                //7、上传操作
                try {
                    multipartFile.transferTo(file);
                    fileNames.add(newFileName);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    model.addAttribute("fileNames",fileNames);

    return "uploadSuc2";
}

servlet3.0 文件上传

springmvc中的bean改成

<bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver"></bean>

bean里面的属性只能在web.xml中写或者使用全注解开发模式

xml文件

  <servlet>
    <!--
        这里的servlet-name是有讲究的,
        如果我们不去修改spring配置文件默认的位置,
        那么springmvc它会去WEB-INF下面找一个叫做springmvc-servlet.xml的文件
    -->
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <!--可以重命名springmvc的文件名-->
      <param-name>namespace</param-name>
      <param-value>springmvc-servlet</param-value>
    </init-param>
    <init-param>
      <!--用来制定上下文的位置-->
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
      <!--需要加上这一行-->
    <multipart-config>
      <max-file-size>200000000</max-file-size>
      <max-request-size>2000000000</max-request-size>
    </multipart-config>
  </servlet>

文件下载

普通方法下载

@RequestMapping("/down2")
public String down2(HttpServletResponse response){
    java.io.BufferedInputStream bis = null;
    java.io.BufferedOutputStream bos = null;

    String filename = "1.jpg";

    String downLoadPath = parentPath + filename;  //注意不同系统的分隔符
    // String downLoadPath =filePath.replaceAll("/", "\\\\\\\\");   //replace replaceAll区别 *****
    System.out.println(downLoadPath);

    try {
        long fileLength = new File(downLoadPath).length();
        response.setContentType("application/x-msdownload;");
        response.setHeader("Content-disposition", "attachment; filename=" + new String(filename.getBytes("utf-8"), "ISO8859-1"));
        response.setHeader("Content-Length", String.valueOf(fileLength));
        bis = new BufferedInputStream(new FileInputStream(downLoadPath));
        bos = new BufferedOutputStream(response.getOutputStream());
        byte[] buff = new byte[2048];
        int bytesRead;
        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
            bos.write(buff, 0, bytesRead);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (bis != null)
            try {
                bis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        if (bos != null)
            try {
                bos.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }
    return null;
}

使用spring自带的ResponseEntity进行下载

@RequestMapping("/down3")
public ResponseEntity<byte[]> export() throws IOException {

    String filename = "1.jpg";
    HttpHeaders headers = new HttpHeaders();
    File file = new File(parentPath + filename);
    if(file.exists()){
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", filename);

        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                headers, HttpStatus.CREATED);
    }else{
        System.out.println(filename+" no exists");
        return null;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容