7

我正在尝试上传带有其他表单数据的文件并通过 MVC 发布到 Web API,但我无法完成。

MVC 端

首先,我在 MVC 获得了提交的表单。这是针对此的操作。

    [HttpPost]
            public async Task<ActionResult> Edit(BrandInfo entity) {

                try {
                    byte[] logoData = null;
                    if(Request.Files.Count > 0) {
                        HttpPostedFileBase logo = Request.Files[0];
                        logoData = new byte[logo.ContentLength];
                        logo.InputStream.Read(logoData, 0, logo.ContentLength);
                        entity.Logo = logo.FileName;
                        entity = await _repo.Update(entity.BrandID, entity, logoData);
                    }
                    else
                        entity = await _repo.Update(entity,entity.BrandID);
                    return RedirectToAction("Index", "Brand");
                }
                catch(HttpApiRequestException e) {
// logging, etc                   
                    return RedirectToAction("Index", "Brand");
                }
            }

下面的代码将 Multipartform 发布到 Web API

string requestUri = UriUtil.BuildRequestUri(_baseUri, uriTemplate, uriParameters: uriParameters);
            MultipartFormDataContent formData = new MultipartFormDataContent();
            StreamContent streamContent = null;
            streamContent = new StreamContent(new MemoryStream(byteData));            
            streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") {
                FileName = "\"" + fileName + "\"",
                Name = "\"filename\""
            };
            streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            formData.Add(streamContent);
            formData.Add(new ObjectContent<TRequestModel>(requestModel, _writerMediaTypeFormatter), "entity");
            return _httpClient.PutAsync(requestUri, formData).GetHttpApiResponseAsync<TResult>(_formatters);

如您所见,我正在尝试使用相同的文件数据和对象发送MultipartFormDataContent。我找不到更好的方式将我的实体发送为ObjectContent. 我也在使用 JSON.Net Serializer

关于提琴手,帖子似乎很成功。

PUT http://localhost:12836/api/brand/updatewithlogo/13 HTTP/1.1
Content-Type: multipart/form-data; boundary="10255239-d2a3-449d-8fad-2f31b1d00d2a"
Host: localhost:12836
Content-Length: 4341
Expect: 100-continue

--10255239-d2a3-449d-8fad-2f31b1d00d2a
Content-Disposition: form-data; filename="web-host-logo.gif"; name="filename"
Content-Type: application/octet-stream

GIF89a��L������X�������wW����������xH�U�)�-�k6�������v6�������̥�v�J���������7����V:�=#�ի�I(�xf�$�������
// byte data
// byte data
'pf�Y��y�ؙ�ڹ�(�;
--10255239-d2a3-449d-8fad-2f31b1d00d2a
Content-Type: application/json; charset=utf-8
Content-Disposition: form-data; name=entity

{"BrandID":13,"AssetType":null,"AssetTypeID":2,"Logo":"web-host-logo.gif","Name":"Geçici Brand","Models":null,"SupplierBrands":null}
--10255239-d2a3-449d-8fad-2f31b1d00d2a--

Web API 端

最后,我在 Web API 端捕捉帖子并尝试解析,但我做不到。因为MultipartFormDataStreamProvider'sFileDataFormData集合总是空的。

[HttpPut]
        public void UpdateWithLogo(int id) {
            if(Request.Content.IsMimeMultipartContent()) {
                var x = 1; // this code has no sense, only here to check IsMimeMultipartContent
            }  

            string root = HttpContext.Current.Server.MapPath("~/App_Data");
            var provider = new MultipartFormDataStreamProvider(root);

            try {
                // Read the form data.
                 Request.Content.ReadAsMultipartAsync(provider);

                 foreach(var key in provider.FormData.AllKeys) {
                     foreach(var val in provider.FormData.GetValues(key)) {
                         _logger.Info(string.Format("{0}: {1}", key, val));
                     }
                 }

                // This illustrates how to get the file names.
                foreach(MultipartFileData file in provider.FileData) {
                    _logger.Info(file.Headers.ContentDisposition.FileName);
                    _logger.Info("Server file path: " + file.LocalFileName);
                }               
            }
            catch(Exception e) {
                throw new HttpApiRequestException("Error", HttpStatusCode.InternalServerError, null);
            }              
        }

我希望你能帮助找出我的错误。

更新

我还意识到,如果我注释掉StreamContentObjectContent仅添加 StringContent,我仍然无法从MultipartFormDataStreamProvider.

4

1 回答 1

5

最后我解决了我的问题,一切都与异步有关:)

正如您在 API 操作方法中看到的那样,我同步调用了ReadAsMultipartAsync方法,但这是一个错误。ContinueWith在我改变了我的代码之后,我不得不调用它,所以我的问题解决了。

var files = Request.Content.ReadAsMultipartAsync(provider).ContinueWith<HttpResponseMessage>(task => {
                    if(task.IsFaulted)
                        throw task.Exception;
// do additional stuff
});
于 2013-03-26T15:45:23.280 回答