首页 > 代码库 > 跨域文件上传解决方案

跨域文件上传解决方案

文件上传在项目中是必不可少的一个环节。一般而言,只要有一个上传页面就可以了  图片直接上传到网站下面。

但是当项目较多,或者项目太大 有好多需要上传文件的需求时,一个通用的文件上传组件就很有必要了。

而且我需要的是文件上传之后是在单独的服务器上(外在体现就是网站与图片不是同一个域名)

这样文件上传页面与当前网站就需要跨域进行上传操作了。

上传过程没有问题,但是上传结束之后的回调操作因为不能跨域存取值而无法进行。

 

通过对网上一些文章的整理,方案如下

 

调用文件上传组件的页面(url=http://localhost:2565/.....)

<body>    <form id="fileform" name = "fileform" enctype="multipart/form-data" target="hideFrame" method="post"            action="http://localhost:13124/Upload/FileHandler.ashx?cb=http://localhost:2565/fileUploadCB.htm">        <input type="file" id="fileSelector" name="fileSelector" />    </form>    <iframe id="hideFrame" name="hideFrame" style="display:none;"></iframe>    <input type="button" id="btnUpload" value="上传" />    <script>        document.querySelector("#btnUpload").onclick = function () {            this.style.backgroundColor = "blue";//上传过程中按钮是蓝色的            document.querySelector("#fileform").submit();        }        function uploadCallBack(rst) {            document.querySelector("#btnUpload").style.backgroundColor = "";//上传结束按钮颜色回复            console.log(rst);        }</script>

 form的target要指定一个隐藏的iframe,这样当前页面才不会因为上传图片而刷新。

实际上就相当于在隐藏的iframe中打开action指定的链接并把form中的数据post过去

至于action的链接中有个参数cb,这个cb的链接在整个操作中至关重要:它是上传结束后回调操作的第一步。

 

上传文件的后台代码(http://localhost:13124/Upload/FileHandler.ashx)

private const int MAX_UPLOAD_SIZE = 2;/// <summary>/// 上传文件/// fileSelector是前台代码中文件控件的name
/// </summary>/// <returns></returns>public string UploadFile(HttpRequest req ,HttpResponse res){ if (req.Files["fileSelector"].ContentLength > MAX_UPLOAD_SIZE * 1024 * 1024) { return String.Format("请上传{0}M以内的文件。", MAX_UPLOAD_SIZE); } string uploadFileName = req.Files["fileSelector"].FileName; string path = HttpContext.Current.Server.MapPath(uploadFileName); req.Files["fileSelector"].SaveAs(path); return "";} /// <summary>/// 上传结束后要重定向到指定链接/// </summary>/// <param name="context"></param>public void ProcessRequest(HttpContext context){ string result = UploadFile(context.Request, context.Response); if (String.IsNullOrEmpty(result)) { result = "上传成功"; } string cbSrc = http://www.mamicode.com/context.Request["CB"]; context.Response.Redirect(cbSrc);}

 

 

注意:cb指定的上传结束后的链接与调用上传组件的页面是同源的。

cb指定的页面(http://localhost:2565/fileUploadCB.htm)

<html xmlns="http://www.w3.org/1999/xhtml"><body>    <script>        alert("成功Oh Yeah!");        parent.uploadCallBack("上传成功!");    </script></body></html>

 

 该页面只是起到一个中转的作用,用于上传结束之后将结果提供给主页面,并执行回调函数。


 

上面给出的只是基本方案。具体的话  还有很多事情要做,上传时传的参数还是要研究一下的  因为这决定了文件的分类,用户归属等。

大部分工作也没必要自己写,有很多成熟的上传插件

如 FineUploader

跨域文件上传解决方案