spring boot实现文件上传下载以及多文件上传

首先是很简单的界面,在resource/static下创建文件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>
<br><br><br>
<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>
<br><br><br>
<a href="/fileDownload">下载</a>
</body>
</html>






//然后是controller层

package com.example.myproject.web;

import org.springframework.stereotype.Controller;
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.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

/**
 * Created by lenovo on 2017/4/27.
 */
@Controller
public class FileController {

    /**
     * 文件上传具体实现方法;
     * @param file
     * @return
     */
    @RequestMapping("/upload")
    @ResponseBody
    public String handleFileUpload(@RequestParam("file")MultipartFile file){
        if(!file.isEmpty()){
            try {
                String fileName = file.getOriginalFilename();
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File("F:\\files\\" + fileName)));
                out.write(file.getBytes());
                out.flush();
                out.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return"上传失败,"+e.getMessage();
            } catch (IOException e) {
                e.printStackTrace();
                return"上传失败,"+e.getMessage();
            }
            return"上传成功";
        }else{
            return"上传失败,因为文件是空的.";
        }
    }
    @RequestMapping(value = "/fileDownload")
    @ResponseBody
        public String download(HttpServletResponse response) throws Exception {
            BufferedInputStream bis = null;
            BufferedOutputStream bos = null;
            //获取下载文件露肩
            String downLoadPath = "F:\\迅雷下载\\day13\\avi\\13.01_常见对象(StringBuffer的概述).avi";

            /*response.setHeader("content-type", "application/octet-stream");

            //获取文件的长度
            long fileLength = new File(downLoadPath).length();
            //设置文件输出类型
            response.setContentType("application/octet-stream");
            //设置输出长度
            response.setHeader("Content-Length", String.valueOf(fileLength));*/
        /********************************************************************/
            //获取输入流
            bis = new BufferedInputStream(new FileInputStream(downLoadPath));
            //输出流
            bos = new BufferedOutputStream(new FileOutputStream(new File("F:\\1.avi")));
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
            //关闭流
            bis.close();
            bos.close();

        return "下载成功";
    }

    @RequestMapping(value="/batch/upload", method= RequestMethod.POST)
    @ResponseBody
    public String handleFileUpload(HttpServletRequest request){
        List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("file");
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        for (int i =0; i< files.size(); ++i) {
            file = files.get(i);
            if (!file.isEmpty()) {
                try {
                   BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(new File("F:\\files\\" + file.getOriginalFilename())));
                   bufferedOutputStream.write(file.getBytes());
                   bufferedOutputStream.flush();
                   bufferedOutputStream.close();
                } catch (Exception e) {
                    return "You failed to upload " + i + " => " + e.getMessage();
                }
            } else {
                return "You failed to upload " + i + " because the file was empty.";
            }
        }
        return "上传成功";
    }
}




//我们要设置一些属性

//在application.properties

#文件上传配置
spring.http.multipart.max-file-size=32MB
spring.http.multipart.max-request-size=128MB

#启动程序,访问http://localhost:8080/file.html即可



  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值