webuploader 跨域

1.upload.jsweb

 // 實例化
        uploader = WebUploader.create({
            pick: {
                id: '#filePicker',
                label: '點擊選擇圖片'
            },
            formData: {
                uid: 123
            },
            dnd: '#dndArea',
            paste: '#uploader',
            swf: 'Scripts/Uploader.swf',
            chunked: true, //分片處理大文件
            chunkSize: 2 * 1024 * 1024,
            server: 'http://localhost:54987/Modules/Test/fileupload.ashx',
            //server:'fileupload2.ashx',
            disableGlobalDnd: true,
            threads: 1, //上傳併發數
            //因爲Http的無狀態特徵,在往服務器發送數據過程傳遞一個進入當前頁面是生成的GUID做爲標示
            formData: { guid: GUID },
            fileNumLimit: 300,
            compress: false, //圖片在上傳前不進行壓縮
            fileSizeLimit: 200 * 1024 * 1024,    // 200 M
            fileSingleSizeLimit: 50 * 1024 * 1024    // 50 M
        });
View Code
uploader.on("uploadBeforeSend", function (obj, data, headers) {
            _.extend(headers, {
                "Origin": "http://localhost:3504",
                "Access-Control-Request-Method": "POST"
            });

        });
View Code
// 文件上傳成功,合併文件。
        uploader.on('uploadSuccess', function (file, response) {
            if (response.chunked) {
                $.post("http://localhost:54987/Modules/Test/MergeFiles.ashx", { guid: GUID, fileExt: response.f_ext },
                function (data) {
                    data = $.parseJSON(data);
                    if (data.hasError) {
                        alert('文件合併失敗!');
                    } else {
                        //alert(decodeURIComponent(data.savePath));
                    }
                });
            }
        });
View Code

2.把 fileupload.ashx MergeFiles(合併) 文件放到另外一個項目中跨域

//若是進行了分片
            if (context.Request.Form.AllKeys.Any(m => m == "chunk"))
            {
                //取得chunk和chunks
                int chunk = Convert.ToInt32(context.Request.Form["chunk"]);//當前分片在上傳分片中的順序(從0開始)
                int chunks = Convert.ToInt32(context.Request.Form["chunks"]);//總分片數
                //根據GUID建立用該GUID命名的臨時文件夾
                string folder = context.Server.MapPath("~/1/" + context.Request["guid"] + "/");
                string path = folder + chunk;

                //創建臨時傳輸文件夾
                if (!Directory.Exists(Path.GetDirectoryName(folder)))
                {
                    Directory.CreateDirectory(folder);
                }

                FileStream addFile = new FileStream(path, FileMode.Append, FileAccess.Write);
                BinaryWriter AddWriter = new BinaryWriter(addFile);
                //得到上傳的分片數據流
                HttpPostedFile file = context.Request.Files[0];
                Stream stream = file.InputStream;

                BinaryReader TempReader = new BinaryReader(stream);
                //將上傳的分片追加到臨時文件末尾
                AddWriter.Write(TempReader.ReadBytes((int)stream.Length));
                //關閉BinaryReader文件閱讀器
                TempReader.Close();
                stream.Close();
                AddWriter.Close();
                addFile.Close();

                TempReader.Dispose();
                stream.Dispose();
                AddWriter.Dispose();
                addFile.Dispose();

                context.Response.Write("{\"chunked\" : true, \"hasError\" : false, \"f_ext\" : \"" + Path.GetExtension(file.FileName) + "\"}");
            }
            else//沒有分片直接保存
            {
                //根據GUID建立用該GUID命名的臨時文件夾
                string folder = context.Server.MapPath("~/1/");
                //創建臨時傳輸文件夾
                if (!Directory.Exists(Path.GetDirectoryName(folder)))
                {
                    Directory.CreateDirectory(folder);
                }
                context.Request.Files[0].SaveAs(context.Server.MapPath("~/1/" + DateTime.Now.ToFileTime() + Path.GetExtension(context.Request.Files[0].FileName)));
                context.Response.Write("{\"chunked\" : false, \"hasError\" : false}");
            }
View Code
public class MergeFiles : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            string guid = context.Request["guid"];
            string fileExt = context.Request["fileExt"];
            string root = context.Server.MapPath("~/1/");
            string sourcePath = Path.Combine(root,guid + "/");//源數據文件夾
            string targetPath = Path.Combine(root, Guid.NewGuid() + fileExt);//合併後的文件

            DirectoryInfo dicInfo = new DirectoryInfo(sourcePath);
            if (Directory.Exists(Path.GetDirectoryName(sourcePath)))
            {
                FileInfo[] files = dicInfo.GetFiles();
                foreach (FileInfo file in files.OrderBy(f => int.Parse(f.Name)))
                {
                    FileStream addFile = new FileStream(targetPath, FileMode.Append, FileAccess.Write);
                    BinaryWriter AddWriter = new BinaryWriter(addFile);

                    //得到上傳的分片數據流
                    Stream stream = file.Open(FileMode.Open);
                    BinaryReader TempReader = new BinaryReader(stream);
                    //將上傳的分片追加到臨時文件末尾
                    AddWriter.Write(TempReader.ReadBytes((int)stream.Length));
                    //關閉BinaryReader文件閱讀器
                    TempReader.Close();
                    stream.Close();
                    AddWriter.Close();
                    addFile.Close();

                    TempReader.Dispose();
                    stream.Dispose();
                    AddWriter.Dispose();
                    addFile.Dispose();
                }
                DeleteFolder(sourcePath);
                context.Response.Write("{\"chunked\" : true, \"hasError\" : false, \"savePath\" :\"" + System.Web.HttpUtility.UrlEncode(targetPath) + "\"}");
                //context.Response.Write("{\"hasError\" : false}");
            }
            else
                context.Response.Write("{\"hasError\" : true}");
        }



        /// <summary>
        /// 刪除文件夾及其內容
        /// </summary>
        /// <param name="dir"></param>
        private static void DeleteFolder(string strPath)
        {
            //刪除這個目錄下的全部子目錄
            if (Directory.GetDirectories(strPath).Length > 0)
            {
                foreach (string fl in Directory.GetDirectories(strPath))
                {
                    Directory.Delete(fl, true);
                }
            }
            //刪除這個目錄下的全部文件
            if (Directory.GetFiles(strPath).Length > 0)
            {
                foreach (string f in Directory.GetFiles(strPath))
                {
                    System.IO.File.Delete(f);
                }
            }
            Directory.Delete(strPath, true);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
View Code

全局 跨域配置安全

 <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*"/>
        <add name="Access-Control-Allow-Headers" value="*"/>
        <add name="Access-Control-Allow-Methods" value="GET,POST,OPTIONS"/>
      </customHeaders>
    </httpProtocol>
  </system.webServer>
View Code

用 http://localhost:3504 代替 *,不安全。服務器

地址是要上傳的地方併發

相關文章
相關標籤/搜索