如何使用js创建form表单,并使用ajax上传文件。

直接上代码:

//file为从file类型input框中获取的的文件对象
var file = fileArr[fileIndex];

//创建表单对象,并加入文件对象
var formFile = new FormData();
formFile.append("file", file); //加入文件对象

//设置ajax参数为表单对象
var data = formFile;
$.ajax({
	type: "post",
	url: "/file/upload",
	dataType: "json",
	data:data,
	cache: false,
	processData: false,
	contentType: false,
	success: function (data) {
		if(data != 'false'){
			toastr.success('操作成功!');
		}else{
			toastr.error('操作失败!');
		}
	},
	error: function (a,b,c) {
		toastr.error('操作失败!');
	}
});

注意,ajax的这三个参数必不可少:

cache: false,
processData: false,
contentType: false,

 

你可能感兴趣的:(file,input)