C#实现HTTP请求文件下载,GET、POST请求的数据流接收

原创 2016-11-02 16:34:43 792
摘要:做项目的时候由于插件Phaser请求audio的时候,不允许跨域,具体提示====》已拦截跨源请求:同源策略禁止读取位于 http://ttyouni.com/1.mp3 的远程资源。(原因:CORS 头缺少 'Access-Control-Allow-Origin')。幸亏只是音乐,要是图片也不允许跨域,就麻烦了。因为以前一直使用图片上传,所以代码也是参照着那里写的,结果,拿到的

做项目的时候由于插件Phaser请求audio的时候,不允许跨域,具体提示====》

已拦截跨源请求:同源策略禁止读取位于 http://ttyouni.com/1.mp3 的远程资源。(原因:CORS 头缺少 'Access-Control-Allow-Origin')。

幸亏只是音乐,要是图片也不允许跨域,就麻烦了。因为以前一直使用图片上传,所以代码也是参照着那里写的,结果,拿到的文件一直是损坏的。

其中看到stream的Length的显示是出现异常,虽然知道是因为网络数据流读取的问题,但是怎么写还是不清楚。

C++的buffer写法倒是会,但是C#的一直没写过。网上搜,关键词一直不对,搜了老久的c#网络请求数据流接收,没有一个有用。

哦,后来搜到个streamreader,可惜人家写的接收类型是string...还是╮(╯﹏╰)╭不会。最后,还是老大出马,拿了个网上的参考地址。

最后才写好的,总觉得一把辛酸泪。

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))
            {//如果已经存在,那么就不需要拷贝了,如果没有,那么就进行拷贝
                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
            }
            // 转换为byte类型
            System.IO.Stream stream = response.GetResponseStream();


            //创建本地文件写入流
            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;//拿到前面那个/,这样为绝对路径,直接保存在整个项目下的upload文件夹下
        return path.Substring(pos, path.Length - pos);
    }
    return "";
}


发布手记

热门词条