SpringMVC实现文件的上传下载

SpringMVC文件上传下载

1. 步骤分析

  • 创建好工程并配置好SpringMVC基本环境,并引入上传文件需要的两个包:commons-fileupload-1.3.1.jar和commons-io-2.4.jar。
  • 创建上传页面upload.jsp
  • 在Spring的核心配置文件中注册上传处理器
  • 编写Controller层,从页面获取到然后存入指定的文件夹
  • 编写下载和显示界面show.jsp
  • 实现controller层下载功能

2. 代码实现

2.1、导入jar包

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

2.2、创建upload.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>图片上传下载</title>
    <style>
        #box{
            width: 600px;
            height: 600px;
            margin: 100px auto;
        }
    </style>
</head>
<body>
<div id="box">
    <form action="/springmvc/oss.do" method="post" enctype="multipart/form-data">
       选择文件:<input type="file" name="img"/><br/>
        <input type="submit" value="提交">
    </form>
</div>
</body>
</html>

2.3、在SpringMVC核心配置文件注册上传处理器

    <mvc:resources mapping="/upload/**" location="/upload/"></mvc:resources>

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8"/>
        <!-- 设置上传文件的大小上限,单位:byte10m=1024k 1k=1024b -->
        <property name="maxUploadSize" value="10240000"/>
    </bean>

2.4、编写Controller层

@RequestMapping("/upload.do")
    public ModelAndView upload(MultipartFile file, HttpServletRequest req) throws IOException {
        // 获得原始文件名称
        String originalFileName = file.getOriginalFilename();
        String suffixName = originalFileName.substring(originalFileName.lastIndexOf("."));
        // 生成新文件名
        String newFlieName = UUID.randomUUID().toString() +suffixName;
        // 保存到指定的文件路径
        String uploadDir = req.getServletContext().getRealPath("/upload");
        File f = new File(uploadDir);
        if(!f.exists()){
            f.mkdir();
      	}
      	file.transferTo(new File(uploadDir,newFlieName));
        System.out.println("文件上传到服务器的位置:" + uploadDir + "/" + newFlieName);
        ModelAndView mv = new ModelAndView();
        mv.addObject("newFlieName",newFlieName);
        mv.addObject("originalFileName",originalFileName);
        mv.setViewName("show");
        return mv;
    }

2.5、编写下载和显示界面show.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>图片上传下载</title>
</head>
<body>
<div>${originalFileName}上传成功!</div>
<img src="<%=request.getContextPath() %>/upload/${newFlieName}" style="width:300px; height: 200px;">
<a href="<%=request.getContextPath() %>/download.do?newImgName=${newFlieName}&originalFileName=${originalFileName}">下载</a>
</body>
</html>

2.6、实现controller层下载功能

@RequestMapping("/download.do")
    public ResponseEntity<byte[]> download(HttpServletRequest request,String newImgName,String originalFileName) throws IOException {
        // 获取文件所在文件夹路径
        String path = request.getServletContext().getRealPath("/upload/")+newImgName;
        // 读取图片
        byte[] imgbody = FileUtils.readFileToByteArray(new File(path));
        // 防止下载乱码
        String downloadImgName = new String(originalFileName.getBytes("UTF-8"), "iso-8859-1");
        // 设置响应头
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentDispositionFormData("attachment",downloadImgName);
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(imgbody, httpHeaders, HttpStatus.OK);
        return responseEntity;
 }

3. 运行测试

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值