前台使用ajax通过formdata传递数据,包含文件数据和其他表单数据。
文件使用<input class="shangchuan" type="file" id="cimg" name="Imgfile" />上传
var post_data = {
goods_name:goods_name,
goods_sort:goods_sort,
goods_price:eval(price),
goods_num:eval(number),
isre:eval(val),
g_detail:$("#g_detail").val()
};
var form=new FormData();
form.append("img",mmp);
form.append("goodsinfo",JSON.stringify(post_data));
var posturl = "http://localhost:8080/E-imgload/goodsimg/addgoods"; // 接收上传文件的后台地址
console.info(form);
$.ajax({
type:"POST",
url:posturl,
contentType: "multipart/form-data",//指定为form-data格式
data: form,
async: false,
processData: false,
contentType: false,
success:function(data){
if(data.code==200){
alert("添加成功");
}else{
alert(data.msg);
}
}
});
后台引入commons-fileupload-1.4.jar,commons-io-2.6.jar
通过Upload解析前台数据。
public Object addgoods(HttpServletRequest req) throws UnsupportedEncodingException{
String goodsinfo = null;
String filename = null;
String imgpath="";
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
// 解决普通输入项中文乱码问题
upload.setHeaderEncoding("utf-8");
List<FileItem> items;
try {
items = upload.parseRequest(req);
for (FileItem item : items) {
if (item.isFormField()) {
String name = item.getFieldName();
if (item.getFieldName().equals("goodsinfo")) {
goodsinfo = item.getString("utf-8");
System.out.println(goodsinfo);
}
}else {
filename=item.getName();
imgpath=filename;
InputStream in = item.getInputStream();
String path=req.getSession().getServletContext().getRealPath("/img/goods");
FileOutputStream out = new FileOutputStream(path+"/"+imgpath);
byte[] bytes = new byte[1024];
int len = 0;
while ((len = in.read(bytes)) != -1) {
out.write(bytes, 0, len);
}
in.close();
out.close();
}
}
} catch (FileUploadException | IOException e1) {
e1.printStackTrace();
}
ObjectMapper mapper = new ObjectMapper();
String rs="error";
Goods goods=new Goods();
try {
goods = mapper.readValue(goodsinfo,goods.getClass());
goods.setG_img_path(imgpath);
rs=this.goodsservice.AddGoods(goods);
} catch (IOException e) {
e.printStackTrace();
}
return rs;
}