【java开发】使用MultipartFile进行文件上传的例子

这是个文件上传的例子。后端使用spring MVC的MultipartFile对象,接收来自页面POST过来的数据。前端页面使用XMLHttpRequest发送文件数据。javascript

后端代码以下:html

package com.zkm.spring3.action;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping(
		value="/test",
		produces = "text/html;charset=UTF-8")  
public class FileUploadTestAction {
    
    @RequestMapping(
    		method = RequestMethod.GET, 
    		value="/showFileUploadPage")  
    public String showFileUploadPage() {
        return "test/file_upload";  
    }  

	@RequestMapping(
			method = RequestMethod.POST, 
			value = "/postFileToServer")
	@ResponseBody
	public String postFileToServer(@RequestParam() MultipartFile fileHandler){
		
		if (fileHandler==null || fileHandler.isEmpty()) return "{\"code\":\"-1\",\"msg\":\"文件上传失败!\"}";
		System.out.println("name: " + fileHandler.getOriginalFilename() + "  size: " + fileHandler.getSize()); 
		
		String pathName = "/data/www/zkm-live/files/";
		String picFullFileName = pathName + UUID.randomUUID().toString() + "_" + fileHandler.getOriginalFilename();
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(picFullFileName); 
			fos.write(fileHandler.getBytes()); // 写入文件
			return "{\"code\":\"0\",\"msg\":\"文件上传成功!\"}";
		} catch (Exception e) {
			e.printStackTrace();
			return "{\"code\":\"-1\",\"msg\":\"文件上传失败!\"}";
		} finally {
			try {
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}

后端使用了spring3注解,有两个action,第一个action用来显示文件上传的页面,不包含任何业务逻辑;第二个action用来接收上传的文件,而后写入服务端本地文件,最后返回带有成功标志的json串。前端

前端代码以下:java

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Upload Files using XMLHttpRequest - Minimal</title>
<script type="text/javascript">
	function fileSelected() {
		var file = document.getElementById('fileToUpload').files[0];
		if (file) {
			var fileSize = 0;
			if (file.size > 1024 * 1024){
				fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString()+ 'MB';
			}else{
				fileSize = (Math.round(file.size * 100 / 1024) / 100).toString()+ 'KB';
			}
			document.getElementById('fileName').innerHTML = 'Name: ' + file.name;
			document.getElementById('fileSize').innerHTML = 'Size: ' + fileSize;
			document.getElementById('fileType').innerHTML = 'Type: ' + file.type;
		}
	}
	function uploadFile() {
		var fd = new FormData();
		fd.append("fileHandler",document.getElementById('fileToUpload').files[0]);
		var xhr = new XMLHttpRequest();
		xhr.upload.addEventListener("progress", uploadProgress, false);
		xhr.addEventListener("load", uploadComplete, false);
		xhr.addEventListener("error", uploadFailed, false);
		xhr.addEventListener("abort", uploadCanceled, false);
		xhr.open("POST", "/test/postFileToServer");
		xhr.send(fd);
	}
	function uploadProgress(evt) {
		if (evt.lengthComputable) {
			var percentComplete = Math.round(evt.loaded * 100 / evt.total);
			document.getElementById('progressNumber').innerHTML = percentComplete.toString()+ '%';
		} else {
			document.getElementById('progressNumber').innerHTML = 'unable to compute';
		}
	}
	function uploadComplete(evt) {
		/* This event is raised when the server send back a response */
		alert(evt.target.responseText);
	}
	function uploadFailed(evt) {
		alert("There was an error attempting to upload the file.");
	}
	function uploadCanceled(evt) {
		alert("The upload has been canceled by the user or the browser dropped the connection.");
	}
</script>
</head>
<body>
<input type="file" name="fileToUpload" id="fileToUpload" onchange="fileSelected();" /> 
<span id="fileName"></span> 
<span id="fileSize"></span> 
<span id="fileType"></span> 
<input type="button" onclick="uploadFile()" value="Upload" /> 
<span id="progressNumber"></span>
</body>
</html>

前端使用XMLHttpRequest提交POST数据。曾尝试用jquery的post方法,但不成功。jquery

最后须要注意的是,前端提交的formData中,有这样一句话:web

fd.append("fileHandler",document.getElementById('fileToUpload').files[0]);

也就是说,fileHandler 是一个关键字,后端接收文件的 MultipartFile 也必须叫这个名字。不然会出现下面的错误:spring

所以,后端的 MultipartFile 命名有两种写法,分别是:json

public String postFileToServer(@RequestParam("fileHandler") MultipartFile multipartFile ){

或:后端

public String postFileToServer(@RequestParam() MultipartFile fileHandler){

对于第一种写法,我彻底可以理解,由于,经过注解进行了绑定。app

可是第二种写法,我以为有点奇怪。jdk编译事后的目标码,变量名字是没有任何意义的,那么先后端是如何实现变量绑定的呢?

 

参考资料:

http://www.cnblogs.com/xiandedanteng/p/4168609.html

相关文章
相关标签/搜索