Html+Ajax+Webservice 实现文件跨域上传
1. 界面HTML
<p >上传文件: <input id="zfiles" type="file" name="file"/></ p> <br /> <input type="button" value="上传" onclick="test()" />
2. JavaScript代码(记得引用Jquery文件哦!!!)
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. Webservice代码
[WebMethod]
public string UploadExcel()
{
string result = "1";
string filePath = "D:\\";//保存文件的地址
var file = HttpContext.Current.Request.Files;
try
{
for (int i = 0; i < file.Count; i++)
{
var f = file[i];
filePath = Path.Combine(filePath, f.FileName);
f.SaveAs(filePath);
}
result = "0";
}
catch(Exception ex)
{
throw new Exception(ex.Message);
}
return result;
}

记得对这句代码取消注释!!!


浙公网安备 33010602011771号