包含图片的form表单提交方法提交方式为ajax(不需要转成base64码)

进行上传之前需要用maven导包

<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>
</dependency>
然后在spring-mvc.xml中添加配置文件

<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="204800"/>
</bean>
配置方面暂时就是这样了,然后是前端方面
先写两个form表单分别为图片提交和表单信息提交

<!--该处为信息提交处,记得要写id-->
<form name="add" id="formSub">
<input type="number" name="ldmCommodityId" id="ldmCommodityId">
<br>
<input type="number" name="ldmLotteryId" id="ldmLotteryId">

</form>
<!--此处为图片信息提交处,同上要有id-->
<form id="uploadPic">
图片: &nbsp;<input type="file" name="storeimgsrc" id="storeimgsrc" accept="imgage/*" onchange="base64()">
</form>
<button type="submit" onclick=postInfo("url")>新增</button>

//图片预览区的div
<div style="float: right" id="imgShow" class="imgShow" hidden=true>
<img id="img_upload_show"/>
</div>


下面就是jQuery部分了(这部分的一些配置就不写出来了)
<script type="text/javascript">

//这是我自己添的图片预览方法
function base64() {

var input = document.querySelector('input[type = "file"]');

var file = input.files[0]
console.log(file);

var reader = new FileReader();
reader.readAsDataURL(file);

reader.onload = function () {
$("#img_upload_show").attr("src", this.result);//将转换后的编码存入src完成预览
}
}


//这是ajax提交方法
function postInfo(url) {

var formData = new FormData($("#uploadPic")[0]);
var json = JSON.stringify($("#formSub").serializeArray());
formData.append("json", json)

$.ajax({
type: "POST",
url: url,
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (response) {
alert(data)
console.log(data);
if (data == "success") {
alert("成功");

} else {
alert("失败";
}
}
})
}
</script>




posted @ 2018-03-30 09:27  什么是无欲无求  阅读(236)  评论(0编辑  收藏  举报