AJAX + WebService 实现文件上传

1. 界面HTML

<p >上传文件: <input id="zfiles" type="file" name="file"/></ p>
<br />
<input type="button" value="上传" onclick="test()" />

2. JavaScript代码

function test() {
var ts = document.getElementById("zfiles").files[0];
var formData = new FormData();
formData.append("file", ts); $.ajax({
url: '/cwbase/service/mdm/ExcelIO.asmx/UploadExcel' ,
type: 'POST',
data: formData,
//async: false,
//cache: false,
contentType: false,
processData: false,
success: function () {
alert('success');
},
error: function () {
alert('error');
}
});
}

3. 后台代码

[WebMethod]
public string UploadExcel()
{
string result = "";
string filePath = "E:\\";
var file = HttpContext.Current.Request.Files;
try
{
for (int i = ; i < file.Count; i++)
{
var f = file[i]; filePath = Path.Combine(filePath, f.FileName); f.SaveAs(filePath);
}
result = "";
}
catch(Exception ex)
{
throw new Exception(ex.Message);
}
return result;
}
上一篇:awk基础03-分支和循环语句


下一篇:基于HTML5实现的超酷摄像头(HTML5 webcam)拍照功能 - photobooth.js