spring mvc multipart file upload

pom.xml

<dependency>
            <groupId>commons-iogroupId>
            <artifactId>commons-ioartifactId>
            <version>${commons-io-version}version>
        dependency>
        <dependency>
            <groupId>commons-fileuploadgroupId>
            <artifactId>commons-fileuploadartifactId>
            <version>${commons-fileupload-version}version>
        dependency>
<dependency>
            <groupId>javax.servletgroupId>
            <artifactId>javax.servlet-apiartifactId>
            <version>3.1.0version>
            <scope>providedscope>
        dependency>
servlet-context.xml


    <beans:bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <beans:property name="defaultEncoding" value="UTF-8" />
        
        <beans:property name="maxUploadSize" value="200000000" />
    beans:bean>

    
    
    
    <beans:bean id="exceptionResolver"
        class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <beans:property name="exceptionMappings">
            <beans:props>
                
                <beans:prop
                    key="org.springframework.web.multipart.MaxUploadSizeExceededException">test/upload-errbeans: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 Uploadh1>
    <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 Uploadh1>
    <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>

你可能感兴趣的:(spring4,fileupload,maven,java,mybatis)