通过 Ajax 向后台发送文件(包括图片)时,其参数类型属于对象。可以创建一个 FormData 对象,然后调用它的 append() 方法来添加字段。
例如:
var formData = new FormData();
formData.append("username", "cedric");
formData.append("tel", 15866666666); //数字123456会被立即转换成字符串 "15866666666"
// HTML 文件类型input,由用户选择
formData.append("userfile", fileInputElement.files[0]);
实例应用
html代码
<div class="form-group">
<label for="upload_crowd_name" class="col-sm-2 control-label">人群名称</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="upload_crowd_name" placeholder="请输入人群名称">
</div>
</div>
<div class="form-group">
<label for="upload_crowd_desc" class="col-sm-2 control-label">人群说明</label>
<div class="col-sm-10">
<textarea class="form-control" id="upload_crowd_desc" cols="20" rows="5"></textarea>
</div>
</div>
<div class="form-group">
<label for="crowd_file" class="col-sm-2 control-label">上传文件</label>
<div class="col-sm-10">
<input type="file" accept=".xlsx" id="crowd_file">
</div>
</div>
js代码
$('.submit').click(function () {
var crowd_name = $.trim($('#upload_crowd_name').val());
var crowd_desc = $.trim($('#upload_crowd_desc').val());
var crowd_file = $('#crowd_file')[0].files[0];
var formData = new FormData();
formData.append("crowd_file",$('#crowd_file')[0].files[0]);
formData.append("crowd_name", crowd_name);
formData.append("crowd_desc", crowd_desc);
$.ajax({
url:'/upload/',
dataType:'json',
type:'POST',
async: false,
data: formData,
processData : false, // 使数据不做处理
contentType : false, // 不要设置Content-Type请求头
success: function(data){
console.log(data);
if (data.status == 'ok') {
alert('上传成功!');
}
},
error:function(response){
console.log(response);
}
});
})
有话要说