业务情况:上传多图,并且图片需要跟用户关联,上传过程还带有其他参数。
java框架:spring
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>formData多图+参数请求测试</title>
</head>
<style>
.choose {
width: 100px;
height: 40px;
line-height: 40px;
text-align: center;
border: 1px solid green;
border-radius: 13px;
display: inline-block;
margin-bottom: 10px;
}
.choose:HOVER{
color: blue;
background-color: #f7f7f7;
cursor: pointer;
}
</style>
<body>
<div class="choose" οnclick="openFile()">选择材料</div>
<div class="choose" οnclick="upload()">上 传</div>
<input type="file" accept="image/*" id="file1" name="image_file1" multiple="multiple" style="display: none">
<input type="file" accept="image/*" id="file2" name="image_file2" style="display: none">
<!-- <img id="img1" src="" class="photo"/>
<img id="img2" src="" class="photo"/> -->
<script src="../res/commons/js/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
/**
* 打开文件选择框
*/
function openFile(){
$('#file1').val('');
$('.photo').attr('src','');
$('#file1').click();
}
document.getElementById("file1").addEventListener('change',readFile,false);
var imgArray = new Array();
var index = 0;
function readFile(){
index = 0;
//this指代被监听的input对象
if(this.files && this.files.length>0){
for(var i=0; i<this.files.length; i++){
var file = this.files[i];
if(!file){
return;
}
if(!/image\/\w+/.test(file.type)){
alert("请确保文件为图像类型");
return false;
}
if(file.size===0){
alert("请确保图片大小不为0");
return false;
}
//通过判断后,将文件读取加载出来显示
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(e){
$('body').append('<img id="img'+(++index)+'" src="" class="photo" style="max-width:200px;display:block"/>');
var img = document.getElementById("img"+(index));
img.src = this.result;
imgArray.push(file);
};
}
}
}
function upload(){
var formdata = new FormData();
if(imgArray.length<=0){
alert('未选择图片,不能上传');
return;
}
for(var i=0 ; i<imgArray.length; i++){
formdata.append("img"+(i+1),imgArray[i]);
}
formdata.append("userName","test");
formdata.append("userPassword","123456");
$.ajax({
type: 'POST',
url : '../formData/test1.do',
contentType: false,//禁止编辑请求头
processData: false,//禁止处理参数
data : formdata,//获得第一个form中的信息,html表现为正面部分
dataType: 'json',
success: function(data){
if(data.status==0){
alert('成功');
}
else{
alert(data.message);
}
},
error: function(data){
alert('当前网络状况不好,请稍候重试。');
}
});
}
</script>
</body>
</html>
package controller;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
import cn.com.startdima.vo.OperateResult;
@Controller
@RequestMapping("/formData")
public class FormDataTest
{
/**
* 测试接收FormData
* @return
*/
@RequestMapping("/test1.do")
@ResponseBody
public OperateResult test1(HttpServletRequest request,String userName,String userPassword)
{
System.out.println("userName="+userName);
System.out.println("userPassword="+userPassword);
OperateResult result = new OperateResult();
try {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
MultipartHttpServletRequest multipartHttpServletRequest =
(MultipartHttpServletRequest) request;
Map<String, MultipartFile> list = multipartHttpServletRequest.getFileMap();
Set<String> keys = list.keySet();
for(String key : keys){
System.out.println("key="+key);
//将图片保存到本地
MultipartFile file = list.get(key);
String resourcePath = "D:/formDataTest";
File path = new File(resourcePath);
if(!path.exists()){
path.mkdirs();
}
File upload = new File("/"+resourcePath+key+".jpg");
file.transferTo(upload);
}
}
result.setStatus(0);
} catch (Exception e) {
e.printStackTrace();
result.setStatus(1);
result.setMessage(e.getMessage());
}
return result;
}
}
测试通过,可以得到各个图片文件的参数名,这样就能用来跟用户的一些参数进行关联,下面可以开始实际应用。