摘要:做項(xiàng)目的時(shí)候由于插件Phaser請(qǐng)求audio的時(shí)候,不允許跨域,具體提示====》已攔截跨源請(qǐng)求:同源策略禁止讀取位于 http://ttyouni.com/1.mp3 的遠(yuǎn)程資源。(原因:CORS 頭缺少 'Access-Control-Allow-Origin')。幸虧只是音樂(lè),要是圖片也不允許跨域,就麻煩了。因?yàn)橐郧耙恢笔褂脠D片上傳,所以代碼也是參照著那里寫的,結(jié)果,拿到的
做項(xiàng)目的時(shí)候由于插件Phaser請(qǐng)求audio的時(shí)候,不允許跨域,具體提示====》
已攔截跨源請(qǐng)求:同源策略禁止讀取位于 http://ttyouni.com/1.mp3 的遠(yuǎn)程資源。(原因:CORS 頭缺少 'Access-Control-Allow-Origin')。
幸虧只是音樂(lè),要是圖片也不允許跨域,就麻煩了。因?yàn)橐郧耙恢笔褂脠D片上傳,所以代碼也是參照著那里寫的,結(jié)果,拿到的文件一直是損壞的。
其中看到stream的Length的顯示是出現(xiàn)異常,雖然知道是因?yàn)榫W(wǎng)絡(luò)數(shù)據(jù)流讀取的問(wèn)題,但是怎么寫還是不清楚。
C++的buffer寫法倒是會(huì),但是C#的一直沒(méi)寫過(guò)。網(wǎng)上搜,關(guān)鍵詞一直不對(duì),搜了老久的c#網(wǎng)絡(luò)請(qǐng)求數(shù)據(jù)流接收,沒(méi)有一個(gè)有用。
哦,后來(lái)搜到個(gè)streamreader,可惜人家寫的接收類型是string...還是╮(╯﹏╰)╭不會(huì)。最后,還是老大出馬,拿了個(gè)網(wǎng)上的參考地址。
最后才寫好的,總覺(jué)得一把辛酸淚。
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)存在,那么就不需要拷貝了,如果沒(méi)有,那么就進(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;//拿到前面那個(gè)/,這樣為絕對(duì)路徑,直接保存在整個(gè)項(xiàng)目下的upload文件夾下 return path.Substring(pos, path.Length - pos); } return ""; }