美文网首页
HttpWebRequest上传超过2G文件问题

HttpWebRequest上传超过2G文件问题

作者: 保罗柴夫斯基 | 来源:发表于2019-04-26 18:43 被阅读0次

    问题

    Unity使用HttpWebRequest上传文件超过2G是没问题的,但是移植到.NET Core里,同样的代码问题就来了!Unity使用.net framework框架。

    解决

    .NET Core使用HttpClient代替HttpWebRequest!

    核心代码

    var fileName = Path.GetFileName(fileNamePath);
    using (var fClient = new HttpClient())
    {
        fClient.MaxResponseContentBufferSize = 256000;
        fClient.Timeout = new TimeSpan(Timeout * 10000L);
        fClient.DefaultRequestHeaders.Add("cookie", this.Session);
        fileStream = File.Open(fileNamePath, FileMode.Open, FileAccess.Read);
        var streamContent = new StreamContent(fileStream);
        streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
        streamContent.Headers.ContentDisposition.Name = "\""+saveName + "\"";
        streamContent.Headers.ContentDisposition.FileName = "\"" + fileName + "\"";
        streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        //string boundary = Guid.NewGuid().ToString();
        string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
        var content = new MultipartFormDataContent(boundary);
        content.Headers.Remove("Content-Type");
        content.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary);
    
        content.Add(streamContent);
    
        var response = await fClient.PostAsync(new Uri(url), content);
        response.EnsureSuccessStatusCode();
        this.Data = await response.Content.ReadAsStringAsync();
    
        streamContent.Dispose();
        fileStream.Dispose();
    }
    

    注意

    • 上传进度使用fileStream.Position
    • .net framework跟.net core之间,相同的代码时,部分功能不一定相同,比如HttpWebRequest上传文件功能

    相关文章

      网友评论

          本文标题:HttpWebRequest上传超过2G文件问题

          本文链接:https://www.haomeiwen.com/subject/vawqnqtx.html