SpringMVC文件上传、下载

导入核心依赖

<dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.4</version>
    </dependency>

    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.4</version>
    </dependency>

springmvc.xml配置

<!--注意这里的id必须是multipartResolver,否则会报Required request part 'file' is not present-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8"/>
        <property name="maxUploadSize" value="10240000"/>
</bean>

前端代码

<body>
<h2>单文件上传</h2>
<form action="upload1" method="post" enctype="multipart/form-data">
    <input type="file" name="file"><br>
    <input type="submit" value="上传"><br>
</form>

<h2>多文件上传1</h2>
<form action="upload2" method="post" enctype="multipart/form-data">
    <input type="file" name="file" multiple="multiple"><br>
    <input type="submit" value="上传"><br>
</form>

<h2>多文件上传2</h2>
<form action="upload3" method="post" enctype="multipart/form-data">
    <input type="file" name="file" ><br>
    <input type="file" name="file2" ><br>
    <input type="file" name="file3" ><br>
    <input type="submit" value="上传"><br>
</form>

<h2>文件下载</h2>
<a href="download?filename=<%=URLEncoder.encode("相机.jpg", "UTF-8")%>">下载</a><br>
</body>

单文件上传

//单文件上传
    @PostMapping("upload1")
    public String upload1(@RequestParam("file") MultipartFile file, HttpServletRequest request){
        //获取工程目录
        String path = request.getServletContext().getRealPath("uploads");
        //判断目录是否存在,若不存在则创建
        File file1 = new File(path);
        if (!file1.exists()){
            file1.mkdirs();
        }
        //获取上传的文件原始名字
        String originalFilename = file.getOriginalFilename();
        //创建一个文件项
        File uploadFile = new File(path + File.separator + UUID.randomUUID().toString() + originalFilename);
        try {
            //将文件域里的文件保存至文件项里
            file.transferTo(uploadFile);
        } catch (IOException e) {
            e.printStackTrace();
            return "上传失败";
        }
        return "success";
    }

多文件上传1

//多文件上传
    @PostMapping("upload2")
    public String upload2(@RequestParam("file") List<MultipartFile> file, HttpServletRequest request){
        //把多文件放进一个list里,通过for循环遍历出来然后进行保存
        String path = request.getServletContext().getRealPath("/uploads/");
        File file1 = new File(path);
        if (!file1.exists()){
            file1.mkdirs();
        }
        for (MultipartFile multipartFile:file){
            String originalFilename = multipartFile.getOriginalFilename();
            File uploadpath = new File(path + File.separator + UUID.randomUUID().toString() + originalFilename);
            try {
                multipartFile.transferTo(uploadpath);
            } catch (IOException e) {
                e.printStackTrace();
                return "上传失败";
            }
        }

        return "success";
    }

多文件上传2

 //多文件上传2
    @PostMapping("upload3")
    public String upload3(MultipartRequest file, HttpServletRequest request){
        //使用工具类进行文件上传
        try {
            UploadUtils.getFile(file, request);
        }catch (Exception e){
            e.printStackTrace();
            return "上传失败";
        }
        return "success";
    }

上传文件封装类

public class UploadUtils {
    public static Map<String, Object> getFile(MultipartRequest files, HttpServletRequest request) {
        //获取工程目录
        String path = request.getServletContext().getRealPath("uploads");
        //使用map集合存放文件域
        Map<String,Object> pathmap=new HashMap<String,Object>();
        try {
            //使用map集合存放文件域
            Map<String, MultipartFile> map = files.getFileMap();
            //通过key取出map集合里的文件项
            Set<String> key=map.keySet();
            for (String string : key) {
                MultipartFile multipartFile = map.get(string);
                String originalFilename = multipartFile.getOriginalFilename();
                File file = new File(path + File.separator + UUID.randomUUID().toString() + originalFilename);
                multipartFile.transferTo(file);
                pathmap.put(string, multipartFile);
            }
        }catch (Exception e){
            e.printStackTrace();

        }
        return pathmap;
    }
}

文件下载

@RequestMapping("download")
    public ResponseEntity<byte[]> download(HttpServletRequest request, @RequestParam("filename") String fileName) throws Exception {
        String realPath = request.getServletContext().getRealPath("uploads");
        System.out.println(realPath);
        File file = new File(realPath + File.separator + fileName);
        fileName = this.getFilename(request, fileName);
        // 通知浏览器以下载的方式打开文件
        HttpHeaders httpHeaders=new HttpHeaders();
        // 通知浏览器以下载的方式打开文件
        httpHeaders.setContentDispositionFormData("attachment",fileName);
        // 定义以二进制流的形式下载返回文件数据
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),httpHeaders, HttpStatus.OK);
    }

    /*
     * 根据浏览器的不同进行编码设置,返回编码后的文件名
     */
    public String getFilename(HttpServletRequest request,String filename) throws Exception {
        // IE不同版本User-Agent中出现的关键词
        String[] IEBrowserKeyWords = {"MSIE", "Trident", "Edge"};
        // 获取请求头代理信息
        String userAgent = request.getHeader("User-Agent");
        for (String keyWord : IEBrowserKeyWords) {
            if (userAgent.contains(keyWord)) {
                //IE内核浏览器,统一为UTF-8编码显示
                return URLEncoder.encode(filename, "UTF-8");
            }
        }
        //火狐等其它浏览器
        return new String(filename.getBytes("UTF-8"), "ISO-8859-1");
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值