js跨域上传文件

前台HTML

 

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml" >
 3 <head>
 4     <title>Untitled Page</title>
 5 </script>
 6 <script type="text/javascript">
 7         function UpladFile() 
 8         {
 9             var fileObj = document.getElementById("file").files[0]; // 获取文件对象
10             var FileController = "http://192.168.1.191/H.ashx";                    // 接收上传文件的后台地址 
11             // FormData 对象
12             var form = new FormData();
13             //form.append("author", "hooyes");                        // 可以增加表单数据
14             form.append("file", fileObj);                           // 文件对象
15             // XMLHttpRequest 对象
16             var xhr = new XMLHttpRequest();
17             xhr.open("post", FileController, true);
18             xhr.onload = function () {
19                 alert("上传完成!");
20             };
21             xhr.send(form);
22         }
23 </script>
24 </head>
25 <body>
26 <input type="file" id="file" name="myfile" />
27 <input type="button" onclick="UpladFile()" value="上传" />
28 </body>
29 </html>

 

后台ashx

 

1 context.Response.AddHeader("Access-Control-Allow-Origin", "*");//跨域必须有的头
2 context.Request.Files["file"].SaveAs(savurl + fileName);

 

 

 

 

posted @ 2014-05-21 10:11  应世玉  阅读(834)  评论(0)    收藏  举报