通过FormData对象可以组装一组用 XMLHttpRequest发送请求的键/值对。它可以更灵活方便的发送表单数据,因为可以独立于表单使用。如果你把表单的编码类型设置为multipart/form-data ,则通过FormData传输的数据格式和表单通过submit() 方法传输的数据格式相同
来源
<form enctype="multipart/form-data" method="post" name="fileinfo">
<label>Your email address:</label>
<input type="email" autocomplete="on" autofocus name="userid" placeholder="email" required size="32" maxlength="64" /><br />
<label>Custom file label:</label>
<input type="text" name="filelabel" size="12" maxlength="32" /><br />
<label>File to stash:</label>
<input type="file" name="file" required />
<input type="submit" value="Stash the file!" />
</form>
var form = document.forms.namedItem("fileinfo");
form.addEventListener('submit', function(ev) {
var oOutput = document.querySelector("div"),
oData = new FormData(form);
oData.append("CustomField", "This is some extra data");
var oReq = new XMLHttpRequest();
oReq.open("POST", "stash.php", true);
oReq.onload = function(oEvent) {
if (oReq.status == 200) {
oOutput.innerHTML = "Uploaded!";
} else {
oOutput.innerHTML = "Error " + oReq.status + " occurred when trying to upload your file.<br \/>";
}
};
oReq.send(oData);
ev.preventDefault();
}, false);
c#
if (context.Request.Files.Count > 0)
{
string dire = "/doc/attach/myTollGateItem/" + forms["id"].ToString() + "/";
string path = context.Server.MapPath(dire);
if (!System.IO.Directory.Exists(path))//判断文件夹是否已经存在
{
System.IO.Directory.CreateDirectory(path);//创建文件夹
}
pub newpub = new pub();
for (int i = 0; i < context.Request.Files.Count; i++)
{
HttpPostedFile f = context.Request.Files[i];
Random rd = new Random();
if (f.FileName != "")
{
string pn = newpub.rdm(10) + DateTime.Now.Millisecond.ToString() + "." + f.FileName.Split('.')[f.FileName.Split('.').Length - 1];
f.SaveAs(path + "/" + pn);
// project_id,
//check_list_id,
//action_id,
//file_path,
//sort_id,
//modify_time,
//modify_user,
//action_sys_id
// toll_gate_project_cklist_file
string sql = "insert into toll_gate_project_cklist_file(check_list_sysid,file_path,sort_id,modify_user)values('" + forms["elem_id"] + "','" + dire + pn + "','" + i.ToString() + "','" + xm + "')";
new DataProvier().RunSql(sql, "", DCoolWeb.Data.DbType.Oracle);
}
}
}