java mvc附件上传_Spring MVC 实现文件的上传和下载

SpringMVC 中,文件的上传,是通过 MultipartResolver 实现的。 所以,如果要实现文件的上传,只要在 spring-mvc.xml 中注册相应的 MultipartResolver 即可。

MultipartResolver 的实现类有两个:

CommonsMultipartResolver

StandardServletMultipartResolver

两个的区别:

第一个需要使用 Apache 的 commons-fileupload 等 jar 包支持,但它能在比较旧的 servlet 版本中使用。

第二个不需要第三方 jar 包支持,它使用 servlet 内置的上传功能,但是只能在 Servlet 3 以上的版本使用。

第一个使用步骤:

/CommonsMultipartResolver 上传用到的两个包/

"commons-fileupload:commons-fileupload:1.3.1",

"commons-io:commons-io:2.4"

如果是maven项目的话直接导入:

commons-fileupload

commons-fileupload

1.3.1

dispatcher-servlet.xml配置:

web.xml:

dispatcher

org.springframework.web.servlet.DispatcherServlet

contextConfigLocation

classpath:dispatcher-servlet.xml

dispatcher

/

后台java(上传、下载)处理代码:

package edu.nf.ch08.controller;

import org.apache.commons.io.FileUtils;

import org.springframework.http.HttpHeaders;

import org.springframework.http.HttpStatus;

import org.springframework.http.MediaType;

import org.springframework.http.ResponseEntity;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.PostMapping;

import org.springframework.web.multipart.MultipartFile;

import org.springframework.web.servlet.ModelAndView;

import java.io.File;

import java.io.IOException;

/**

上传文件的网页html:

Title

文件上传

File:

a81a20b832af23309cb9f81196dd7a81.png

上传成功后转发的jsp(下载文件)页面:

Created by IntelliJ IDEA.

User: wangl

Date: 2018/11/2

Time: 09:56

To change this template use File | Settings | File Templates.

--%>

Title

${fileName}

64c9a217a6e9a827ead05fd47f6fe51e.png

项目结构:

2de56b4be16bd23cee18c0c8c807011d.png