ajax上传图片
springmvc上传示例:
服务器端代码:
@RequestMapping(value="/addbrands",produces = "application/json")
@ResponseBody
public MyAjaxResult addbrand(MultipartFile myfile,String brand,String type) {
System.out.println(myfile);
System.out.println(brand);
System.out.println(type);
return MyAjaxResult.success("上传成功");
}
前端代码:
var image_file=document.getElementById("changeImg1");//文件
var fenlei=document.getElementById("type").value;//附加内容
var pinpai=document.getElementById("brand").value;//附加内容
var formData = new FormData();//封装数据
formData.append('myfile',image_file.files[0]);//添加文件
formData.append("type",fenlei);//添加内容
formData.append("brand",pinpai);//添加内容
//发送请求
$.ajax({
url: '${path}/type/addbrands',//请求路径
type: 'POST',
cache: false,
data: formData,//数据
processData: false,
contentType: false
}).done(function(res) { //回调函数
console.log(res)
}).fail(function(res) {
console.log(res)
});