在form表单里上传图片

需要上传多个图片分别上传,本来提供的工具类里上传一张可以form表单对象实现 后台用MultipartFile file

var formdata = new FormData($("#inputForm")[0]);

@RequestMapping(value="/uploadImg")
@ResponseBody
public String uploadImg(MultipartFile file,HttpServletRequest request,HttpServletResponse response) throws IOException{

String name = file.getOriginalFilename();

但是两张图片就不能在后台接到数据了,原因是name="file"的才能被接收,第二个不会接收

解决方案一:用两个form提交 问题就解决了  但是不适用外层还有一层form

<body>
<form enctype="multipart/form-data" id="inputForm1" modelAttribute="bankAdminist" action="" method="post" class="form-horizontal">
<div class="control-group">
<label class="control-label">*LOGO:</label>
<div class="controls">
<input type="hidden" id="image" name="pcLogopic" value="" />
<input type="file" name="file" id="file1"/><input type="button" value="上传" onclick="uploadImage()" class="btn btn-primary"/>

</div>
</div>
</form>
<form enctype="multipart/form-data" id="inputForm2" modelAttribute="bankAdminist" action="" method="post" class="form-horizontal">
<div class="control-group">
<label class="control-label">*LOGO:</label>
<div class="controls">
<input type="hidden" id="image2" name="appLogopic" value="" />

<input type="file" name="file" id="file2"/><input type="button" value="上传" onclick="uploadImage2()" class="btn btn-primary"/>

</div>
</div>
</form>

<script type="text/javascript">

function uploadImage(){
var file=$("#file1").val();
var num=1;
upload(file,num);
}
function uploadImage2(){
var num=2
var file=$("#file2").val();
upload(file,num);
}
function upload(file,num){
if(file==""){
alert("请选择上传的文件!");
return false ;
}
var form = document.getElementById("inputForm"+num);
alert(file+"---"+form)
//得到formdata对象
var formdata = new FormData(form);
formdata.append('file',file);
//ajax异步上传图片
//返回的filename类似 front/a.jpg
alert(JSON.stringify(formdata));
$.ajax({
url : "/momo/picture/####.do",
type : "POST",
data : formdata,
//dataType: "json",
cache : false,
contentType : false, //不可缺
processData : false, //不可缺
success:function(filename){
},
error: function (returndata) {
alert(JSON.stringify(returndata));
}
});
}

解决方案二:用h5  的<input type="file" name="file" id="file1" multiple="multiple"/>

<input type="file" name="file" id="file1" multiple="multiple"/><input type="button" value="上传" onclick="uploadImage()" class="btn btn-primary"/>

function uploadImage(){
var file=$("#file1").val();
var num=1;
upload(file,num);
}

function upload(file,num){

//得到formdata对象
var files= $("#file"+num).get(0).files;
//如果有选择图片则上传图片
var formdata = new FormData();
if(files.length>0){
for(var i=0;i<files.length;i++){
formdata.append('file',files[i]);
}
}

//ajax异步上传图片
//返回的filename类似 front/a.jpg
$.ajax({
url : '',
type : 'POST',
data : formdata,

上一篇:【Git】 GitLab服务器社区版安装与配置


下一篇:Android本机号码及Sim卡状态的获取