做項目的時候由於插件Phaser請求audio的時候,不允許跨域,具體提示====》
已攔截跨源請求:同源策略禁止讀取位於 http://ttyouni.com/1.mp3 的遠程資源。(原因:CORS 頭缺少 'Access-Control-Allow-Origin')。
幸虧只是音樂,要是圖片也不允許跨域,就麻煩了。因為以前一直使用圖片上傳,所以代碼也是參照着那里寫的,結果,拿到的文件一直是損壞的。
其中看到stream的Length的顯示是出現異常,雖然知道是因為網絡數據流讀取的問題,但是怎么寫還是不清楚。
C++的buffer寫法倒是會,但是C#的一直沒寫過。網上搜,關鍵詞一直不對,搜了老久的c#網絡請求數據流接收,沒有一個有用。
哦,后來搜到個streamreader,可惜人家寫的接收類型是string...還是╮(╯﹏╰)╭不會。最后,還是老大出馬,拿了個網上的參考地址。
最后才寫好的,總覺得一把辛酸淚。
參考的地址:http://www.jb51.net/article/57068.htm
1 public string CopyFileByUrl(string url) 2 { 3 string name = url.Substring(url.LastIndexOf('/') + 1);//獲取名字 4 string fileFolder = UploadConfigContext.UploadPath; 5 string filePath = Path.Combine(fileFolder, name);//存放地址就是本地的upload下的同名的文件 6 if (!Directory.Exists(fileFolder)) 7 Directory.CreateDirectory(fileFolder); 8 9 string returnPath = GetSimplePath(filePath);//需要返回的路徑 10 if (File.Exists(filePath)) 11 {//如果已經存在,那么就不需要拷貝了,如果沒有,那么就進行拷貝 12 return returnPath; 13 } 14 HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest; 15 request.Method = "GET"; 16 request.ProtocolVersion = new Version(1, 1); 17 HttpWebResponse response = request.GetResponse() as HttpWebResponse; 18 if (response.StatusCode == HttpStatusCode.NotFound) 19 { 20 return string.Empty;//找不到則直接返回null 21 } 22 // 轉換為byte類型 23 System.IO.Stream stream = response.GetResponseStream(); 24 25 26 //創建本地文件寫入流 27 Stream fs = new FileStream(filePath, FileMode.Create); 28 byte[] bArr = new byte[1024]; 29 int size = stream.Read(bArr, 0, (int)bArr.Length); 30 while (size > 0) 31 { 32 fs.Write(bArr, 0, size); 33 size = stream.Read(bArr, 0, (int)bArr.Length); 34 } 35 fs.Close(); 36 stream.Close(); 37 return returnPath; 38 }
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;//拿到前面那個/,這樣為絕對路徑,直接保存在整個項目下的upload文件夾下
return path.Substring(pos, path.Length - pos);
}
return "";
}
