Springboot文件上传与下载

一、创建简单的springboot-web项目

二、文件上传属性配置

#默认支持文件上传
spring.http.multipart.enabled =true
spring.http.multipart.file-size-threshold =0
# 上传文件的临时目录
#spring.http.multipart.location=E:/upload/temp/
# 最大支持文件大小
spring.http.multipart.max-file-size =100MB
# 最大支持请求大小
spring.http.multipart.max-request-size =100Mb

三、文件上传代码

1.Controller层代码:

@RestController
public class UploadController {
    private static final Logger LOGGER = LoggerFactory.getLogger(UploadController.class);

    @GetMapping("/toUpload")
    public String upload() {
        return "upload";
    }

    @PostMapping("/upload")
    public String UploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "请选择文件";
        }
   //获取文件名
        String fileName = file.getOriginalFilename();
        String filePath = "C:/Users/upload/";
        File dest = new File(filePath + fileName);
        try {
            file.transferTo(dest);
            LOGGER.info("上传成功");
            return "上传成功";
        } catch (IOException e) {
            LOGGER.error(e.toString(), e);
        }
        return "上传失败!";
    }
}

2.jsp代码

<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-type" content="text/html; charset=UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
    <title>单文件上传</title>
</head>
<body>
<form method="post" action="/upload" enctype="multipart/form-data">
    <input type="file" name="file"><br>
    <input type="submit" value="提交">
</form>
</body>
</html>

四、文件下载代码

@RequestMapping(value = "/download", method = RequestMethod.GET)
    @ResponseBody
    public String testDownload(HttpServletResponse res,HttpServletRequest request) {
        String fileName = "xxx.txt";
        String filePath = "D:/uploadFile";
        File file = new File(filePath + "/" + fileName);
        System.out.println(file);
        if (file.exists()){//判断文件是否存在
            //判断浏览器是否为火狐
            try {
                if ("FF".equals(getBrowser(request))) {
                    // 火狐浏览器 设置编码new String(realName.getBytes("GB2312"), "ISO-8859-1");
                    fileName = new String(fileName.getBytes("GB2312"), "ISO-8859-1");
                }else{
                    fileName = URLEncoder.encode(fileName, "UTF-8");//encode编码UTF-8 解决大多数中文乱码
                    fileName = fileName.replace("+", "%20");//encode后替换空格  解决空格问题
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            res.setContentType("application/force-download");//设置强制下载
            res.setHeader("Content-Disposition", "attachment;filename=" + fileName);//设置文件名
            byte[] buff = new byte[1024];// 用来存储每次读取到的字节数组
            //创建输入流(读文件)输出流(写文件)
            BufferedInputStream bis = null;
            OutputStream os = null;
            try {
                os = res.getOutputStream();
                bis = new BufferedInputStream(new FileInputStream(file));
                int i = bis.read(buff);
                while (i != -1) {
                    os.write(buff, 0, buff.length);
                    os.flush();
                    i = bis.read(buff);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (os != null){
                    try {
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }else {
            return "文件不存在!!!";
        }
        return "download success";
    }
 
    /**
     * @Title: getBrowser
     * @Description: 判断客户端浏览器
     * @return String
     * @author
     * @date
     */
    private static String getBrowser(HttpServletRequest request) {
        String UserAgent = request.getHeader("USER-AGENT").toLowerCase();
        if (UserAgent != null) {
            if (UserAgent.indexOf("msie") != -1)
                return "IE";
            if (UserAgent.indexOf("firefox") != -1)
                return "FF";
            if (UserAgent.indexOf("safari") != -1)
                return "SF";
        }
        return null;
    }
}

五、测试

 

posted @ 2019-03-11 11:19  少说点话  阅读(1362)  评论(2编辑  收藏  举报
网站运行: