Spring MVC文件上传和下载

基础代码
本文代码:https://download.csdn.net/download/qq_43499543/19356175

一、文件上传

添加Maven依赖

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

在spring配置文件中配置文件上传解析器

 <!--配置文件上传解析器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- 设置上传文件最大尺寸为1MB-->
        <property name="maxUploadSize" value="1048576"></property>
    <!-- 字符编码-->
        <property name="defaultEncoding" value="UTF-8"></property>
    </bean>
1.单文件上传

1)controller

@Controller
public class FileUploadController {
    @RequestMapping("fileUpload")
    public String fileUpLoad(@RequestParam(value = "file",required = false)MultipartFile file, HttpServletRequest request, ModelMap modelMap){
        //服务器端upload文件夹的物理路径
        String path = request.getSession().getServletContext().getRealPath("upload");
        System.out.println(path);
        String fileName = file.getOriginalFilename();   //获取文件名
        File targetFile = new File(path,fileName);  //实例化文件
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        try{
            //将文件保存到相应位置
            file.transferTo(targetFile);
        }catch (Exception e){
            e.printStackTrace();
        }
        modelMap.put("fileUrl",request.getContextPath()+"/upload/"+fileName);
        return "success";
    }
}

2)index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<body>
<h2>Hello World!</h2>
<form action="${pageContext.request.contextPath}/fileUpload" method="post" enctype="multipart/form-data">
    <input type="file" name="file"/><br>
    <input type="submit" value="上传"/><br>
</form>
</body>
</html>

3)运行

注意:upload指服务器中的目录,不是项目中的upload目录,如果使用的是Tomcat服务器,可以在Tomcat目录/webapp/项目名下查找

2.多文件上传

1)controller
添加如下方法

@RequestMapping("fileUpload2")
    public String fileUpLoad2(@RequestParam(value = "files",required = false) List<MultipartFile> files, HttpServletRequest request, @RequestParam("description") String description){
        if(!files.isEmpty() && files.size()>0){
            for(MultipartFile file:files){
                String originalFilename = file.getOriginalFilename();   //获取文件名
                String path = request.getSession().getServletContext().getRealPath("upload");
                File filePath = new File(path);
                if(!filePath.exists()){
                    filePath.mkdirs();
                }
                //文件重命名
                String newFileName = description+"_"+ UUID.randomUUID()+"_"+originalFilename;
                try {
                    file.transferTo((new File(path,newFileName)));
                } catch (IOException e) {
                    e.printStackTrace();
                    return "error";
                }
            }
            return "success";
        }
        else
            return "error";
    }

2)index.jsp
添加如下表单:

<form action="${pageContext.request.contextPath}/fileUpload2" method="post" enctype="multipart/form-data">
    文件描述:<input type="text" name="description"><br>
    <input type="file" name="files" multiple="multiple"/><br>
    <input type="submit" value="上传"/><br>
</form>

error.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<body>
<h2>失败!</h2>
</body>
</html>

3)运行

二、文件下载

1)修改FileUploadController
FileUploadController文件上传controller中的fileUpLoad方法添加model.put("fileName",fileName);使得页面可以获取文件名,便于通过文件名进行下载
2)新建FileDownloadController

@Controller
public class FileDownloadController {
    @RequestMapping("fileDownload")
    public ResponseEntity<byte[]> fileDownload(HttpServletRequest request, @RequestParam("fileName")String fileName, Model model) throws IOException {
        //下载文件路径
        String path = request.getServletContext().getRealPath("/upload");
        //创建文件对象
        File file = new File(path + File.separator + fileName);
        //设置响应头
        HttpHeaders headers = new HttpHeaders();
        //显示文件名,解决乱码问题
        String  downloadFileName = new String(fileName.getBytes("UTF-8"),"ISO-8859-1");
        //通知浏览器以下载方式(attachment)的形式下载返回文件数据
        headers.setContentDispositionFormData("attachment",downloadFileName);
        //定义以二进制数据流(最常见的文件下载方式)的形式下载返回文件数据
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        //使用String MVC框架的ResponseEntity对象封装返回下载数据
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
    }

}

3)修改success.jsp
添加如下语句

<a href="${pageContext.request.contextPath}/fileDownload?fileName=${requestScope.fileName}">${requestScope.fileName}</a>

3)运行,上传文件后在success页面可以通过点击文件名进行下载操作

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值