spring mvc multipart file upload

8 篇文章 0 订阅
5 篇文章 0 订阅
pom.xml

<dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>${commons-io-version}</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>${commons-fileupload-version}</version>
        </dependency>
<dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
servlet-context.xml

<!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 -->
    <beans:bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <beans:property name="defaultEncoding" value="UTF-8" />
        <!-- 指定所上传文件的总大小不能超过200M。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->
        <beans:property name="maxUploadSize" value="200000000" />
    </beans:bean>

    <!-- enctype="multipart/form-data" -->
    <!-- SpringMVC在超出上传文件限制时,会抛出org.springframework.web.multipart.MaxUploadSizeExceededException -->
    <!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 -->
    <beans:bean id="exceptionResolver"
        class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <beans:property name="exceptionMappings">
            <beans:props>
                <!-- 遇到MaxUploadSizeExceededException异常时,自动跳转到/WEB-INF/jsp/error_fileupload.jsp页面 -->
                <beans:prop
                    key="org.springframework.web.multipart.MaxUploadSizeExceededException">test/upload-err</beans:prop>
            </beans:props>
        </beans:property>
    </beans:bean>
MultipartFileUpload.java

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.multipart.MultipartFile;

/**
 * upload files
 * 
 * @author L
 */
public class MultipartFileUpload {

    // app
    public static final String APP_IMG_UPLOAD_URL = "\\resources\\app\\upload\\imgs\\";
    public static final String APP_VIDEO_UPLOAD_URL = "\\resources\\app\\upload\\video\\";
    // web front
    public static final String WEB_FRONT_IMG_UPLOAD_URL = "\\resources\\front\\upload\\imgs\\";
    public static final String WEB_FRONT_VIDEO_UPLOAD_URL = "\\resources\\front\\upload\\video\\";
    // web rear
    public static final String WEB_REAR_IMG_UPLOAD_URL = "\\resources\\rear\\upload\\imgs\\";
    public static final String WEB_REAR_VIDEO_UPLOAD_URL = "\\resources\\rear\\upload\\video\\";

    protected HttpServletRequest httpServletRequest;

    // single
    protected MultipartFile multipartFile;
    protected String multipartFileName;
    protected String desciption;
    protected int size;
    protected byte[] bytes;
    protected BufferedOutputStream bufferedOutputStream;
    protected FileOutputStream fileOutputStream;
    protected File file;
    /**
     * Directory relative address
     */
    protected String directoryRelativeAddress;
    // multipart
    protected MultipartFile[] multipartFiles;
    /**
     * File an absolute address
     */
    protected String fileAbsoluteAddress;
    /**
     * Directory real address
     */
    protected String directoryAbsoluteAddress;

    public MultipartFileUpload() {
    }

    /**
     * single file constructor
     * 
     * @param httpServletRequest
     * @param multipartFile
     * @param desciption
     * @param pathName
     */
    public MultipartFileUpload(HttpServletRequest httpServletRequest, MultipartFile multipartFile, String desciption,
            String directoryRelativeAddress) {
        super();
        this.httpServletRequest = httpServletRequest;
        this.multipartFile = multipartFile;
        this.desciption = desciption;
        this.directoryRelativeAddress = directoryRelativeAddress;
    }

    /**
     * multipart file constructor
     * 
     * @param httpServletRequest
     * @param desciption
     * @param pathName
     * @param multipartFiles
     */
    public MultipartFileUpload(HttpServletRequest httpServletRequest, String desciption,
            String directoryRelativeAddress, MultipartFile[] multipartFiles) {
        super();
        this.httpServletRequest = httpServletRequest;
        this.desciption = desciption;
        this.directoryRelativeAddress = directoryRelativeAddress;
        this.multipartFiles = multipartFiles;
    }

    /**
     * Perform a single file upload operations
     * 
     * @throws IOException
     */
    public void singleFileUpload() throws IOException {
        // To determine whether a file is NULL, if not NULL
        if (!this.multipartFile.isEmpty()) {
            // Get the file name
            getMultipartFileName();
            // Get the byte stream
            getBytes();
            // Absolute directory Settings file storage
            setDirectoryAbsoluteAddress();
            // Absolute address Settings file storage
            setFileAbsoluteAddress();
            // Create a new file
            setFile();
            // Create a new file output stream
            setFileOutputStream();
            // Create a new buffer output stream
            setBufferedOutputStream();
            // Write data to a specified output stream, the basis of not
            // necessarily lead to the underlying system written for each byte
            this.bufferedOutputStream.write(this.bytes);
            // Release the buffer output stream, and close
            this.bufferedOutputStream.close();
        }
    }

    /**
     * A single file upload multiple calls to perform multiple file upload
     * operation
     * 
     * @throws IOException
     */
    public void multipartFileUpload() throws IOException {
        if (!this.multipartFiles.equals(null) && this.multipartFiles.length > 0)
            // Traverse the file list
            for (int i = 0; i < this.multipartFiles.length; i++) {
                this.multipartFile = this.multipartFiles[i];
                // Perform a single file upload operations
                this.singleFileUpload();
            }
    }

    /**
     * 
     * @param request
     * @return
     */
    protected String getDirectoryAbsoluteAddress(HttpServletRequest request, String directoryRelativeAddress) {
        return request.getServletContext().getRealPath("/") + directoryRelativeAddress;
    }

    protected void setBufferedOutputStream() {
        this.bufferedOutputStream = new BufferedOutputStream(this.fileOutputStream);
    }

    protected void setFileOutputStream() throws FileNotFoundException {
        this.fileOutputStream = new FileOutputStream(this.file);
    }

    protected void setFile() {
        this.file = new File(this.fileAbsoluteAddress);
    }

    protected void getMultipartFileName() {
        this.multipartFileName = this.multipartFile.getOriginalFilename();
    }

    protected void getBytes() throws IOException {
        this.bytes = this.multipartFile.getBytes();
    }

    protected void setDirectoryAbsoluteAddress() {
        this.directoryAbsoluteAddress = this.getDirectoryAbsoluteAddress(this.httpServletRequest,
                this.directoryRelativeAddress);
    }

    protected void setFileAbsoluteAddress() {
        this.fileAbsoluteAddress = this.directoryAbsoluteAddress + this.multipartFileName;
    }

}
FileUploadController.java

@Controller
@Scope(value = "prototype")
public class FileUploadController {
    @RequestMapping(value = "/singleUpload")
    public String singleUpload(HttpServletRequest request) {
        return "test/single-upload";
    }

    @RequestMapping(value = "/singleImage", method = RequestMethod.POST)
    public @ResponseBody Message singleImage(@RequestParam("uploadVideo") MultipartFile file, String desc,
            HttpServletRequest request) {
        MultipartFileUpload multipartFileUpload;
        try {
            multipartFileUpload = new MultipartFileUpload(request, file, desc, MultipartFileUpload.APP_IMG_UPLOAD_URL);
            multipartFileUpload.singleFileUpload();
            return new Message("You have successfully uploaded ", true);
        } catch (IOException e) {
            return new Message("You failed to upload :" + e.getMessage(), false);
        }
    }

    @RequestMapping(value = "/singleSave", method = RequestMethod.POST)
    public @ResponseBody String singleSave(@RequestParam("file") MultipartFile file, @RequestParam("desc") String desc,
            HttpServletRequest request) {
        System.out.println("File Description:" + desc);
        MultipartFileUpload multipartFileUpload;
        try {
            multipartFileUpload = new MultipartFileUpload(request, file, desc, MultipartFileUpload.APP_IMG_UPLOAD_URL);
            multipartFileUpload.singleFileUpload();
            return "You have successfully uploaded ";
        } catch (IOException e) {
            return "You failed to upload :" + e.getMessage();
        }
        // finally {
        // return "Unable to upload. File is empty.";
        // }
    }

    @RequestMapping(value = "/multipleUpload")
    public String multiUpload() {
        return "test/multiple-upload";
    }

    @RequestMapping(value = "/multipleSave", method = RequestMethod.POST)
    public @ResponseBody String multipleSave(@RequestParam("file") MultipartFile[] files, HttpServletRequest request) {
        MultipartFileUpload multipartFileUpload = new MultipartFileUpload(request, "",
                MultipartFileUpload.APP_IMG_UPLOAD_URL, files);
        try {
            multipartFileUpload.multipartFileUpload();
            return "You have successfully uploaded ";
        } catch (IOException e) {
            return "You failed to upload :" + e.getMessage();
        }

    }
}
multipart-upload.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<html>
<body>
    <h1>Multiple File Upload</h1>
    <form method="post" enctype="multipart/form-data" action="multipleSave">
        Upload File 1: <input type="file" name="file"> <br /> Upload
        File 2: <input type="file" name="file"> <br /> Upload File 3:
        <input type="file" name="file"> <br /> Upload File 4: <input
            type="file" name="file"> <br /> <br /> <br /> <input
            type="submit" value="Upload">
    </form>
</body>
</html>
single-upload.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><html>
<body>
    <h1>Single File Upload</h1>
    <form method="post" enctype="multipart/form-data" action="singleSave">
        Upload File: <input type="file" name="file"> <br />
        <br /> Description: <input type="text" name="desc" /> <br />
        <br />
        <input type="submit" value="Upload">
    </form>
</body>
</html>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring MVC中的@RequestMapping注解可以用于处理HTTP请求,并将请求的参数绑定到处理方法的参数上。而在处理上传文件的情况下,可以使用@RequestPart注解将文件绑定到处理方法的参数上。 @RequestPart注解用于将请求的某个部分(如文件)绑定到处理方法的参数上。它通常与@RequestParam一起使用,用于处理HTTP POST请求中的FormData部分或者Multipart请求中的文件部分。 使用@RequestPart注解时,需要注意以下几点: 1. @RequestPart注解的参数可以是任何类型,但通常使用MultipartFile或者byte[]来表示文件类型。 2. 需要注意的是,如果@RequestPart注解的参数类型不是MultipartFile或者byte[],则需要使用consumes参数指定媒体类型为"multipart/form-data"。 3. 在处理方法中,使用@RequestPart注解的参数将自动绑定到请求中与参数名称匹配的部分。例如,如果请求中有一个名为file的文件部分,那么使用@RequestPart("file") MultipartFile file将绑定该文件部分到file参数上。 4. 如果请求中没有与参数名称匹配的部分,那么将会抛出异常。 下面是一个使用@RequestPart注解处理文件上传的例子: ```java @Controller @RequestMapping("/upload") public class UploadController { @PostMapping("/file") public String uploadFile(@RequestPart("file") MultipartFile file) { // 处理文件上传逻辑 return "success"; } } ``` 在上面的例子中,我们使用@RequestPart注解将名为file的文件部分绑定到MultipartFile类型的file参数上。处理方法可以根据具体的业务逻辑,对上传的文件进行处理。 总而言之,使用@RequestPart注解可以很方便地处理上传文件的情况,将请求的文件部分绑定到处理方法的参数上,方便进行文件上传的业务逻辑处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值