亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

C#實(shí)現(xiàn)HTTP請求文件下載,GET、POST請求的數(shù)據(jù)流接收

Original 2016-11-02 16:34:43 831
abstract:做項(xiàng)目的時候由于插件Phaser請求audio的時候,不允許跨域,具體提示====》已攔截跨源請求:同源策略禁止讀取位于 http://ttyouni.com/1.mp3 的遠(yuǎn)程資源。(原因:CORS 頭缺少 'Access-Control-Allow-Origin')。幸虧只是音樂,要是圖片也不允許跨域,就麻煩了。因?yàn)橐郧耙恢笔褂脠D片上傳,所以代碼也是參照著那里寫的,結(jié)果,拿到的

做項(xiàng)目的時候由于插件Phaser請求audio的時候,不允許跨域,具體提示====》

已攔截跨源請求:同源策略禁止讀取位于 http://ttyouni.com/1.mp3 的遠(yuǎn)程資源。(原因:CORS 頭缺少 'Access-Control-Allow-Origin')。

幸虧只是音樂,要是圖片也不允許跨域,就麻煩了。因?yàn)橐郧耙恢笔褂脠D片上傳,所以代碼也是參照著那里寫的,結(jié)果,拿到的文件一直是損壞的。

其中看到stream的Length的顯示是出現(xiàn)異常,雖然知道是因?yàn)榫W(wǎng)絡(luò)數(shù)據(jù)流讀取的問題,但是怎么寫還是不清楚。

C++的buffer寫法倒是會,但是C#的一直沒寫過。網(wǎng)上搜,關(guān)鍵詞一直不對,搜了老久的c#網(wǎng)絡(luò)請求數(shù)據(jù)流接收,沒有一個有用。

哦,后來搜到個streamreader,可惜人家寫的接收類型是string...還是╮(╯﹏╰)╭不會。最后,還是老大出馬,拿了個網(wǎng)上的參考地址。

最后才寫好的,總覺得一把辛酸淚。

public string CopyFileByUrl(string url)
        {
            string name = url.Substring(url.LastIndexOf('/') + 1);//獲取名字
            string fileFolder = UploadConfigContext.UploadPath;
            string filePath = Path.Combine(fileFolder, name);//存放地址就是本地的upload下的同名的文件
            if (!Directory.Exists(fileFolder))
                Directory.CreateDirectory(fileFolder);

            string returnPath = GetSimplePath(filePath);//需要返回的路徑
            if (File.Exists(filePath))
            {//如果已經(jīng)存在,那么就不需要拷貝了,如果沒有,那么就進(jìn)行拷貝
                return returnPath;
            }
            HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
            request.Method = "GET";
            request.ProtocolVersion = new Version(1, 1);
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            if (response.StatusCode == HttpStatusCode.NotFound)
            {
                return string.Empty;//找不到則直接返回null
            }
            // 轉(zhuǎn)換為byte類型
            System.IO.Stream stream = response.GetResponseStream();


            //創(chuàng)建本地文件寫入流
            Stream fs = new FileStream(filePath, FileMode.Create);
            byte[] bArr = new byte[1024];
            int size = stream.Read(bArr, 0, (int)bArr.Length);
            while (size > 0)
            {
                fs.Write(bArr, 0, size);
                size = stream.Read(bArr, 0, (int)bArr.Length);
            }
            fs.Close();
            stream.Close();
            return returnPath;
        }

Copy代碼
public string GetSimplePath(string path)
{
    //E:\Upload\cms\day_150813\1.jpg
    path = path.Replace(@"\", "/");
    int pos = path.IndexOf("Upload");
    if (pos != -1)
    {
        pos = pos - 1;//拿到前面那個/,這樣為絕對路徑,直接保存在整個項(xiàng)目下的upload文件夾下
        return path.Substring(pos, path.Length - pos);
    }
    return "";
}


Release Notes

Popular Entries