栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring MVC 实现文件的上传下载

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring MVC 实现文件的上传下载

一、Spring MVC 实现文件的上传下载 1、文件上传 1.1 单文件上传

(1)底层使用的是 Apache fileupload 组件完成上传功能,Spring MVC 只是对其进行了封装,简化开发
pom.xml


      commons-io
      commons-io
      2.6
    
    
      commons-fileupload
      commons-fileupload
      1.3.3

(2)JSP 页面

input 的 type 为 fileform 表单的 method 设置为 postform 表单的 enctype 设置为 multipart/form-data

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>


    Title


    

(3)Controller

@Controller
@RequestMapping("/file")
public class UploadController {

    @PostMapping("/upload")
    public String upload(@RequestParam("img") MultipartFile img, HttpServletRequest request){
        if(img.getSize() > 0){
            String path = request.getSession().getServletContext().getRealPath("file");
            String fileName = img.getOriginalFilename();
            File filePath = new File(path);
            if(!filePath.exists()){
                filePath.mkdir();
            }
            File file = new File(path, fileName);
            try {
                img.transferTo(file);
                request.setAttribute("src", "/file/"+fileName);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return "upload";
        }
        return null;
    }
}

(4)springmvc.xml



(5)图片加载不出来的几个原因:

所有的请求都会被 DispatcherServlet 当作逻辑请求去做映射,由于图片属于静态资源,不应该再将其访问路径交由 DispatcherServlet 来管理,应当采用默认的方式去加载。
在 web.xml 进行如下配置


    default
    *.png


在 springmvc.xml 文件中添加




上述两个标签须同时存在。

JSP 页面中标签固定写死路径时应当注意的问题

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>


    Title


    

Spring MVC 实现文件的上传下载

当 "file"未加斜杠时,表示访问的当前目录下的文件,当前 upload.jsp 的访问路径为 http://localhost:8080/file,故而不加斜杠,其访问路径应当为 http://localhost:8080/file/file/1.png。
当 "file"未加斜杠时,表示访问的表示该目录为根目录的一个子目录,当前 项目的根目录为 http://localhost:8080/,故而访问路径应当为 http://localhost:8080/file/1.png。

idea 中 Tomcat 的配置问题




ApplicationContext 可用于设置根目录,当 ApplicationContext 设置为 /springmvc 时,项目的根目录则相应的更改为 http;//localhost:8080/springmvc,若要访问 file 文件夹下的 1.png,则访问路径应当为 http;//localhost:8080/springmvc/file/1.png。

1.2、多文件上传

1、uploads.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>


    Title


    
file1:
file2:
file3:

2、Controller

@PostMapping("/uploads")
public String uploads(@RequestParam("imgs") MultipartFile[] imgs, HttpServletRequest request){
     List list = new ArrayList<>();
     for (MultipartFile img: imgs) {
         if(img.getSize() > 0){
             String path = request.getSession().getServletContext().getRealPath("/file");
             String fileName = img.getOriginalFilename();
             File pathFile = new File(path);
             if (!pathFile.exists()){
                 pathFile.mkdir();
             }

             File file = new File(path, fileName);

             try {
                 img.transferTo(file);
                 list.add("/file/" + fileName);
             } catch (IOException e) {
                 e.printStackTrace();
             }
         }
     }
     request.setAttribute("list", list);
     return "uploads";
 }
2、文件下载

(1)download.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>


    Title


    1.png
2.png
3.png

Controller

@GetMapping("/download")
public void download(String fileName, HttpServletRequest request, HttpServletResponse response){
    if(fileName != null){
        String path = request.getSession().getServletContext().getRealPath("file");
        File file = new File(path, fileName);
        OutputStream outputStream = null;
        if(file.exists()) {
            // response.setContentType(MIME)的作用是使客户端浏览器区分不同种类的数据,
            // 并根据不同的MIME调用浏览器内不同的程序嵌入模块来处理相应的数据。
            // 强制下载 application/force-download
            response.setContentType("application/force-download");
            // Content-Disposition中指定的类型是文件的扩展名,
            // 并且弹出的下载对话框中的文件类型是按照文件的扩展名显示的,
            // 保存后,文件以filename的值命名,保存类型以Content中设置的为准。
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

            try {
                outputStream = response.getOutputStream();
                outputStream.write(FileUtils.readFileToByteArray(file));
                outputStream.flush();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if(outputStream != null){
                    try {
                        outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/726372.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号