asp.net core 3.1 MultipartFormDataContent multipart/form-data MIME type.


1.多文件上传,也可以继续添加其他参数,只是参数内容要转为byte[]因为使用ByteArrayContent 他的入参是byte[]

 public async Task<FileInfoUploadResponse> Upload(SourceMaterialParamDto source)
        {
            var chatbotId = WebUtility.UrlEncode(source.ChatbotId);
            var url = string.Format(_massp.MateriaUploadUrl, _massp.Host, _massp.Version, chatbotId);
            using (var message = new MultipartFormDataContent())
            {
                foreach (var item in source.FormFiles)
                {
                    var fileContent = new ByteArrayContent(item.Data);
                    if (!new FileExtensionContentTypeProvider().Mappings.TryGetValue(item.Extension, out var contenttype)) throw new Exception("文件格式不存在");//item.Extension=".png" item.FileName="text.png"
                    fileContent.Headers.ContentType = new MediaTypeHeaderValue(contenttype);
                    //fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue($"form-data;name=\"{item.FileName}\";filename=\"{item.FileName}\"");
                    fileContent.Headers.Add("Content-Disposition", $"form-data; name=\"{item.FileName}\"; filename=\"{item.FileName}\"");
                    message.Add(fileContent, item.FileName, item.FileName);
                }
                var date = DateTimeOffset.Now;
                var time = date.ToString("r");
                string token = CreateAuthorizationToken(time);
                message.Headers.Add("UploadMode", source.UploadMode);
                _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("ctToken", token);
                _httpClient.DefaultRequestHeaders.Date = date;
                _httpClient.DefaultRequestHeaders.Host = _massp.AppIp;
                var response = await _httpClient.PostAsync(url, message);
                if (response.StatusCode != HttpStatusCode.OK) return new FileInfoUploadResponse() { ErrorCode = (int)response.StatusCode, ErrorMessage = response.StatusCode.ToString() };
                var rlt = await response.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject<FileInfoUploadResponse>(rlt);
            }
        }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM