先上h5代码
<form id="formId" class="am-form am-form-horizontal" enctype="multipart/form-data">
<div class="am-form-group">
<label for="materialplace" class="am-u-sm-3 am-form-label">地址
</label>
<div class="am-u-sm-9">
<input type="text" id="address" name="address" placeholder="请输入地址">
</div>
</div>
<div class="am-form-group">
<label for="user-intro" class="am-u-sm-3 am-form-label">图片上传</label>
<div class="am-u-sm-9">
<input type="file" name="img" size="20" style="margin-top: 5px;" />
</div>
</div>
</form>
<div class="am-form-group">
<div class="am-u-sm-9 am-u-sm-push-3" style="margin-top: 10px;margin-bottom: 20px;">
<button type="button" onclick="submit()" class="am-btn am-btn-primary" >保存图片和地址</button>
</div>
</div>
j使用ajax提交表单
<script>
function submit() {
console.log("into submit2")
var formData = new FormData($("#formId")[0]);
$.ajax({
async : false,
cache : false,
type : "post",
data : formData,
url : '你的后端地址!',
dataType : 'json',
contentType: false, //必须
processData: false, //必须
success : function(data) {
if(data.success){
alert("添加成功")
}else{
alert("添加失败")
}
},
error : function(){
console.log('error');
}
});
}
</script>
java接收代码
@RequestMapping("/addtask")
public void addtask(HttpServletRequest request, HttpServletResponse response)
throws FileUploadException, IOException {
System.err.println("into addtask------------");
try {
// 解析请求中的数据
MultipartHttpServletRequest mpRequest = (MultipartHttpServletRequest) request;
MultipartFile file = mpRequest.getFile("img");
String path;
String osName = System.getProperties().getProperty("os.name");
if (osName.equals("Linux")) {
path = "/usr/local/img/";
} else {
path = "D:\\upload";
}
// 上传文件的真实名称
String name = file.getOriginalFilename();
//保存在服务器中的文件名
String imageUrl = uploadFile(file, path);
//具体ajax返回对象 可以自定义
ExtResult ext = ExtResult.NEW();
ext.setSuccess(true);
ext.setMsg("添加成功");
ResponseUtils.OutJSON(response, ext);
} catch (Exception e) {
e.printStackTrace();
ExtResult ext = ExtResult.NEW();
ext.setSuccess(false);
ResponseUtils.OutJSON(response, ext);
}
}
public String uploadFile(MultipartFile file, String path) throws IOException{
//上传文件的真实名称
String name = file.getOriginalFilename();
//System.out.println(name);
//获取后缀名
String suffixName = name.substring(name.lastIndexOf("."));
//System.out.println(suffixName);
//自定义随机数
String hash = Integer.toHexString(new Random().nextInt());
String fileName = hash + suffixName;
//System.out.println(fileName);
File tempFile = new File(path, fileName);
if(!tempFile.getParentFile().exists()){
tempFile.getParentFile().mkdir();
}
if(tempFile.exists()){
tempFile.delete();
}
tempFile.createNewFile();
file.transferTo(tempFile);
return tempFile.getName();
}