在平时的项目中,我们会遇到各种各样的上传图片,大多数情况下我们会选择各种各样的插件进行上传,然后返回一个图片url,在进行相关其他业务
如果不用各种插件,运用ajax实现页面上传图片也是可以的,这里用到了formData
首先看一下formData的基本用法:FormData对象,可以把所有表单元素的name与value组成一个queryString,提交到后台。只需要把 form 表单作为参数传入 FormData 构造函数即可:
var form = document.getElementById("uploadPicForm");
var formData = new FormData(form);
这样就可以把formData作为参数直接通过调用ajax进行图片上传和表提交
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="${pageContext.request.contextPath}/scripts/js/jquery-1.11.1.min.js"></script>
<title>表单里上传图片</title>
</head>
<body>
<div>
<form action="${pageContext.request.contextPath}/do/uploadControl/saveInfo" method="post" id="uploadPicForm" name="uploadPicForm" enctype="multipart/form-data">
<input id="id" name="id" value="这是id"/>
<br>
<input id="age" name="age" value="这是age"/>
<br>
<input type="file" name="uploadFile" id="uploadFile" onChange="uploadPicForm.url.value=this.value" />
<input type="text" id="url" name="url" />
<input type="button" id="it" value="上传" style="height:29px;margin-left: -5px;" onclick="doUpload()" />
<br>
<input type="submit" value="提交" />
</form>
</div>
</body>
<script type="text/javascript">
var ctx = "${pageContext.request.contextPath}";
function doUpload(){
var form = document.getElementById("uploadPicForm");
var formData = new FormData(form)
$.ajax({
url: ctx+'/do/uploadControl/uploadPic' ,
type: 'POST',
data: formData,
dataType: "json",
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
if(returndata.success){
$("#url").val(returndata.data);
alert('成功');
return;
}
},
error: function (returndata) {
alert(returndata.msg);
//alert("上传失败");
}
});
}
</script>
</html>