上传的文件总是大小为零

时间:2018-04-06 12:14:00

标签: c# asp.net-mvc

我正在尝试将文件上传到网络API,因此我有以下代码

public async Task<Token> upload(string fullMd5, IEnumerable<HttpPostedFileBase> files)
        {

            string uploadUrl = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
            // Call CMS API 
            string jsonContent = string.Empty;
            HttpClientHandler handler = new HttpClientHandler();
            using (var client = new HttpClient())
            {

                using (var content = new MultipartFormDataContent())
                {

                    var filesData = new MultipartFormDataContent();
                    foreach (var item in files)
                    {
                        HttpContent filecontent = new StreamContent(item.InputStream);
                        filecontent.Headers.ContentType = new MediaTypeHeaderValue(item.ContentType);
                        filecontent.Headers.ContentLength += item.InputStream.Length;
                        filecontent.Headers.ContentDisposition = new ContentDispositionHeaderValue("multipart/form-data")
                        {
                            Name = "file",
                            FileName = item.FileName,

                        };
                        content.Add(filecontent);
                    }




                    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + userObj.access_token);
                    client.DefaultRequestHeaders.Add("Api-version", "2.4");
                    client.DefaultRequestHeaders.Add("CMSId", UserId);

                    var response = await client.PostAsync(uploadUrl, content);

                    jsonContent = await response.Content.ReadAsStringAsync();
                }
            }
            var result = JsonConvert.DeserializeObject<Token>(jsonContent);
            return result;
        }
}
API接收文件但是损坏了零大小,API运行良好,因为我使用postman测试,我尝试在使用SaveAs发送之前保存文件,它在我发送文件的方式上运行良好

1 个答案:

答案 0 :(得分:0)

尝试使用这些标题的postAsync

using (var client = new HttpClient(handler) {BaseAddress = new Uri(_host)})
            {
                var requestContent = new MultipartFormDataContent();
                var fileContent = new StreamContent(fileInfo.OpenRead());
                fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                    {
                        Name = "\"file\"",
                        FileName = "\"" + fileInfo.Name + "\""
                    };
                fileContent.Headers.ContentType =
                    MediaTypeHeaderValue.Parse(MimeMapping.GetMimeMapping(fileInfo.Name));
                var folderContent = new StringContent(folderId.ToString(CultureInfo.InvariantCulture));

                requestContent.Add(fileContent);
                requestContent.Add(folderContent, "\"folderId\"");

                var result = client.PostAsync("Company/AddFile", requestContent).Result;
            }