参考网址:http://www.tuicool.com/articles/2EnMBz
JAVA
package com.hmkcode.controllers;
import java.io.IOException;
import java.util.Calendar;
import java.util.Iterator;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.util.FileCopyUtils;
import com.hmkcode.vo.UploadedFile;
@Controller
@RequestMapping("/cont")
public class RestController {
UploadedFile ufile;
public RestController(){
System.out.println("init RestController");
ufile = new UploadedFile();
}
@RequestMapping(value = "/get/{value}", method = RequestMethod.GET)
public void get(HttpServletResponse response,@PathVariable String value){
try {
response.setContentType(ufile.type);
response.setContentLength(ufile.length);
FileCopyUtils.copy(ufile.bytes, response.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody String upload(MultipartHttpServletRequest request, HttpServletResponse response) {
//0. notice, we have used MultipartHttpServletRequest
//1. get the file from the request object
Iterator<String> itr = request.getFileNames();
MultipartFile mpf = request.getFile(itr.next());
System.out.println(mpf.getOriginalFilename() +" uploaded!");
try {
ufile.length = mpf.getBytes().length;
ufile.bytes= mpf.getBytes();
ufile.type = mpf.getContentType();
ufile.name = mpf.getOriginalFilename();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//2. send it back to the client as <img> that calls get method
//we are using getTimeInMillis to avoid server cached image
return "<img src='http://localhost:8080/spring-mvc-file-upload/rest/cont/get/"+Calendar.getInstance().getTimeInMillis()+"' />";
}
}
配置文件
<beans .....> <context:component-scan base-package="com.hmkcode.controllers" /> <mvc:annotation-driven /> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/> </beans>
<script type="text/javascript" > //using jquery.form.js function uploadJqueryForm(){ $('#result').html(''); $("#form2").ajaxForm({ success:function(data) { //$('#result').text(data+" uploaded by Jquery Form plugin!"); $('#result').html(data); }, dataType:"text" }).submit(); }
HTML
<script src="http://code.jquery.com/jquery-1.9.1.js"></script> <script src="http://malsup.github.com/jquery.form.js"></script>
//using FormData() object
function uploadFormData(){
$('#result').html('');
var oMyForm = new FormData();
oMyForm.append("file", file2.files[0]);
$.ajax({
url: '<strong>http://localhost:8080/spring-mvc-file-upload/rest/cont/upload</strong>',
data: oMyForm,
dataType: 'text',
processData: false,
contentType: false,
type: 'POST',
success: function(data){
// $('#result').html(data+ " uploaded by FormData!");
$('#result').html(data);
}
});
}
</script>
</head>
<body> <h1>SpringMVC - File Upload with/without Ajax</h1> <!-- Form 1 --> <i>Uploading File Without Ajax</i><br/> <form id="form1" method="post" action="/spring-mvc-file-upload/rest/cont/upload" enctype="multipart/form-data"> <!-- File input --> <input name="file" id="file" type="file" /><br/> <input type="submit" value="Upload" /> </form> <hr/> <i>Uploading File With Ajax</i><br/>
<!-- Form 2 --> <form id="form2" method="post" action="/spring-mvc-file-upload/rest/cont/upload" enctype="multipart/form-data"> <!-- File input --> <input name="file2" id="file2" type="file" /><br/> </form> <button value="Submit" onclick="uploadJqueryForm()" >Upload</button><i>Using JQuery Form Plugin</i><br/> <button value="Submit" onclick="uploadFormData()" >Upload</button><i>Using FormData Object</i> <div id="result"></div> </body> </html>