前言

这里用ajax文件上传,并携带几个参数,网上查到的大多都是没带参数只有文件的。
由于我项目代码太多,这里只给出关键代码。

操作

我用的SSM框架,传之前,先在WEB-INF/dispatcherServlet-servlet.xml中配置​multipartResolver​

<!-- 文件上传 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传文件的最大尺寸为1MB -->
<property name="maxUploadSize" value="1048576" />
<!-- 字符编码 -->
<property name="defaultEncoding" value="UTF-8" />
</bean>

前端代码

html部分(主要代码)

<form  method="post" class="form-horizontal" id="addform"  enctype="multipart/form-data">
<div class="form-group">
<label class="col-sm-3 control-label">商品编码</label>
<div class="col-sm-8 controls">
<input type="text" value="" class="form-control" name="code"
id="product_code" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">商品名称</label>
<div class="col-sm-8 controls">
<input type="text" value="" class="form-control" name="name"
id="product_name" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">商品类型</label>
<div class="col-sm-8 controls">
<select class="form-control productTypeId" name="type.id" id="product_type">
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">商品品牌</label>
<div class="col-sm-8 controls">
<input type="text" value="" class="form-control" name="brand" id="product_brand"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">商品数量</label>
<div class="col-sm-8 controls">
<input type="text" class="form-control" name="num" id="product_num"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">商品价格</label>
<div class="col-sm-8 controls">
<input type="text" class="form-control" name="price" id="product_price"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">商品介绍</label>
<div class="col-sm-8 controls">
<input type="text" value="" class="form-control" name="intro" id="product_intro"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">商品状态</label>
<div class="col-sm-8 controls">
<select class="form-control productTypeId" name="status" id="product_status">
<option value="1">在售</option>
<option value="0">下架</option>
</select>
</div>
</div>
<div class="form-group">
<label for="file" class="col-sm-3 control-label">商品图片</label>
<div class="col-sm-8 controls">
<input type="file" class="form-control" name="file" id="file"/>
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" class="btn btn-gmtx-define1 center-block">
添加
</input>
</div>
</div>
</form>

javascript部分(主要代码)

function addProduct() {
//先获取表单中输入的值
var code=$('#product_code').val();
var name=$('#product_name').val();
var type=parseInt($('#product_type option:selected').val());
var brand=$('#product_brand').val();
var num=$('#product_num').val();
var price=$('#product_price').val();
var intro=$('#product_intro').val();
var status=parseInt($('#product_status option:selected').val());
var myform=new FormData();
myform.append('file',$('#file')[0].files[0]);
myform.append('code',code);
myform.append('name',name);
myform.append("type.id",type);
myform.append('brand',brand);
myform.append('num',num);
myform.append('price',price);
myform.append('intro',intro);
myform.append('status',status);

$.ajax({
url:'/ssm_test/productinfo/addProduct',
type:'post',
async:'true',
cache: false,
data:myform,
contentType: false,
processData:false,
dataType:'json',
success:function (data) {
if (data.success){
swal({
title:"系统提示",
text:'添加成功',
type:'success'
});
//先置空添加对话框中的表单内容
var code=$('#product_code').val('');
var name=$('#product_name').val('');
// var type=$('#product_type option:selected').val();
var brand=$('#product_brand').val('');
var num=$('#product_num').val('');
var price=$('#product_price').val('');
var intro=$('#product_intro').val('');
// var status=$('#product_status option:selected').val();
$('#addProduct').modal('hide');
$('#table').bootstrapTable("refresh");
}else{

}
}
});
}

后端代码

实体类

package com.ssm.pojo;

public class ProductInfo {
// 商品基本信息(部分)
private int id; // 商品编号
private String code; // 商品编码
private String name; // 商品名称
// 关联属性
private Type type; // 商品类型

private String brand; // 商品品牌
private String pic; // 商品小图
private int num; // 商品数量
private double price; // 商品价格
private String intro; // 商品介绍
private int status; // 商品状态

private double priceFrom;
private double priceTo;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getCode() {
return code;
}

public void setCode(String code) {
this.code = code;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getIntro() {
return intro;
}

public void setIntro(String intro) {
this.intro = intro;
}

public String getBrand() {
return brand;
}

public void setBrand(String brand) {
this.brand = brand;
}

public double getPrice() {
return price;
}

public void setPrice(double price) {
this.price = price;
}

public int getStatus() {
return status;
}

public void setStatus(int status) {
this.status = status;
}

public String getPic() {
return pic;
}

public void setPic(String pic) {
this.pic = pic;
}

public int getNum() {
return num;
}

public void setNum(int num) {
this.num = num;
}

public double getPriceFrom() {
return priceFrom;
}

public void setPriceFrom(double priceFrom) {
this.priceFrom = priceFrom;
}

public double getPriceTo() {
return priceTo;
}

public void setPriceTo(double priceTo) {
this.priceTo = priceTo;
}

public Type getType() {
return type;
}

public void setType(Type type) {
this.type = type;
}

@Override
public String toString() {
return "ProductInfo{" +
"id=" + id +
", code='" + code + '\'' +
", name='" + name + '\'' +
", type=" + type +
", brand='" + brand + '\'' +
", pic='" + pic + '\'' +
", num=" + num +
", price=" + price +
", intro='" + intro + '\'' +
", status=" + status +
", priceFrom=" + priceFrom +
", priceTo=" + priceTo +
'}';
}
}

control层

//添加商品
@RequestMapping(value = "/addProduct",produces = "text/html;charset=UTF-8")
@ResponseBody
public String addProduct(ProductInfo pi, HttpServletRequest req, ModelMap model,
@RequestParam(value = "file",required = false)MultipartFile file){
//服务器端upload文件夹物理路径
String path=req.getSession().getServletContext().getRealPath("product_images");
//获取文件名
String fileName=file.getOriginalFilename();
//实例化一个File对象,表示目标文件(含物理路径)
File targetFile=new File(path,fileName);
if(!targetFile.exists()){
targetFile.mkdirs();
}
try{
//将上传文件写到服务器上指定的文件
file.transferTo(targetFile);
pi.setPic(fileName);
productInfoService.addProductInfo(pi);
return "{\"success\":\"true\",\"message\":\"商品添加成功\"}";
}catch (Exception e){
return "{\"success\":\"false\",\"message\":\"商品添加失败\"}";
}
}

service层

@Override
public void addProductInfo(ProductInfo pi) {
productInfoDao.save(pi);
}

Dao层

//添加商品
@Insert("insert into product_info(code,name,tid,brand,pic,num,price,intro,status)" +
"values(#{code},#{name},#{type.id},#{brand},#{pic},#{num},#{price},#{intro},#{status})")
@Options(useGeneratedKeys = true,keyProperty = "id")
void save(ProductInfo pi);