首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >springboot-2-springboot的文件上传和下载

springboot-2-springboot的文件上传和下载

作者头像
用户5640963
发布2019-07-26 12:11:38
2.1K0
发布2019-07-26 12:11:38
举报
文章被收录于专栏:卯金刀GG卯金刀GG

单文件上传

1, 需要使用thymeleaf模板: http://www.cnblogs.com/wenbronk/p/6565834.html

src/main/resource/template/file.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
    <head>
        <title>Hello World!</title>
    </head>
    <body>
       <form method="POST" enctype="multipart/form-data" action="/upload"> 
           <p>文件:<input type="file" name="file" /></p>
           <p><input type="submit" value="上传" /></p>
       </form>
    </body>
</html>

文件上传方法

package com.iwhere.main.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

/**
 * 文件上传controller
 * 
 * @RestController 相当于同时 @Controller和@ResponseBody两个注解
 * 
 * @author wenbronk
 * @time 2017年4月6日 下午2:43:03 2017
 */
@RestController
public class FileUploadController {

    /**
     * 文件上传
     * 
     * @return
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String handlFileUpload(@RequestParam("file") MultipartFile file) {

        if (file.isEmpty()) {
            return "文件是空的";
        }

        // 读取文件内容并写入 指定目录中
        String fileName = file.getOriginalFilename();
        // String suffixName = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID() + "|+=|-|" + fileName;

        File dest = new File("E:/test/" + fileName);
        // 判断目录是否存在
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }

        try {
            file.transferTo(dest);
        } catch (IOException e) {
            return "后台也不知道为什么, 反正就是上传失败了";
        }
        return "上传成功";
    }
}

多文件上传:

1, thymeleaf

src/main/resource/template/multifile.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
    <head>
        <title>Hello World!</title>
    </head>
    <body>
       <form method="POST" enctype="multipart/form-data" action="/batch/upload"> 
           <p>文件1:<input type="file" name="file" /></p>
           <p>文件2:<input type="file" name="file" /></p>
           <p>文件3:<input type="file" name="file" /></p>
           <p><input type="submit" value="上传" /></p>
       </form>
    </body>
</html>

2, 多文件上传方法

/**
     * 多文件上传
     * 类似单文件上传, 遍历
     * @return
     */
    @RequestMapping(value = "multiUpload", method = RequestMethod.POST)
    public String handleMultiFileupload(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");

        for (MultipartFile multipartFile : files) {
            if (multipartFile.isEmpty()) {
                return "文件是空的";
            }

            // 读取文件内容并写入 指定目录中
            String fileName = multipartFile.getOriginalFilename();
            // String suffixName =
            // fileName.substring(fileName.lastIndexOf("."));
            fileName = UUID.randomUUID() + "|+=|-|" + fileName;

            File dest = new File("E:/test/" + fileName);
            // 判断目录是否存在
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }

            try {
                multipartFile.transferTo(dest);
            } catch (IOException e) {
                return "后台也不知道为什么, 反正就是上传失败了";
            }
        }
        return "上传成功";
    }

文件下载

/**
     * 文件下载
     * 
     * @return
     */
    @RequestMapping("/download")
    public String downLoadFile(HttpServletRequest request, HttpServletResponse response) {
        // 文件名可以从request中获取, 这儿为方便, 写死了
        String fileName = "rtsch_ex.json";
        // String path = request.getServletContext().getRealPath("/");
        String path = "E:/test";
        File file = new File(path, fileName);

        if (file.exists()) {
            // 设置强制下载打开
            response.setContentType("application/force-download");
            // 文件名乱码, 使用new String() 进行反编码
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);

            // 读取文件
            BufferedInputStream bi = null;
            try {
                byte[] buffer = new byte[1024];
                bi = new BufferedInputStream(new FileInputStream(new File("")));
                ServletOutputStream outputStream = response.getOutputStream();
                int i = -1;
                while (-1 != (i = bi.read(buffer))) {
                    outputStream.write(buffer, 0, i);
                }
                return "下载成功";
            } catch (Exception e) {
                return "程序猿真不知道为什么, 反正就是下载失败了";
            } finally {
                if (bi != null) {
                    try {
                        bi.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return "文件不存在";
    }

文件下载时, 最容易出现文件名乱码的问题, 这儿使用new String() 进行反编码,

String downname = new String(filename.getBytes("gbk"),"iso8859-1");

当然还有个不太稳的方法:

URLEncoder.encode(fileName, "UTF-8"));
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 单文件上传
  • 多文件上传:
  • 文件下载
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档