您的位置:首页 > 编程语言 > Java开发

spring mvc multipart file upload

2015-11-09 16:44 525 查看
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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息