首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Multipart/form-data请求为空

Multipart/form-data请求为空
EN

Stack Overflow用户
提问于 2018-01-23 16:54:15
回答 2查看 2.2K关注 0票数 2

我正在尝试上传一张图片和一些MultipartFormDataContent对象中的json数据。但是由于某些原因,我的webapi没有正确地接收请求。最初,api使用415响应直接拒绝该请求。为了解决这个问题,我向WebApiConfig.cs添加了一个用于多部分/表单数据的xml格式化程序

代码语言:javascript
复制
 public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        // Configure Web API to use only bearer token authentication.
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
        config.Formatters.XmlFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data"));

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }

这似乎在很大程度上是有效的,我使用ARC测试了它,它接收到了multipart的所有部分,唯一的问题是字符串内容没有出现在表单中,它出现在文件中,但我将其归因于请求没有格式化为StringContent对象。

我目前遇到的问题是,我的Xamarin应用程序在发送多部分请求时似乎没有发布任何内容。当请求到达API控制器时,内容标头和所有内容都在那里,但是文件和表单字段都是空的。

在做了一些研究之后,我似乎不得不写一个自定义的MediaTypeFormatter,但我找到的似乎没有一个是我正在寻找的。

下面是我的代码的其余部分:

Api控制器:

代码语言:javascript
复制
[HttpPost]
    public SimpleResponse UploadImage(Image action)
    {
        SimpleResponse ReturnValue = new SimpleResponse();

        try
        {
            if (HttpContext.Current.Request.Files.AllKeys.Any())
            {
                var httpPostedFile = HttpContext.Current.Request.Files["uploadedImage"];
                var httpPostedFileData = HttpContext.Current.Request.Form["imageDetails"];

                if (httpPostedFile != null) 
                {
                    MiscFunctions misctools = new MiscFunctions();

                    string fileName = User.Identity.Name + "_" + misctools.ConvertDateTimeToUnix(DateTime.Now) + ".jpg";
                    string path = User.Identity.Name + "/" + DateTime.Now.ToString("yyyy-mm-dd");
                    string fullPath = path + fileName;

                    UploadedFiles uploadedImageDetails = JsonConvert.DeserializeObject<UploadedFiles>(httpPostedFileData);

                    Uploaded_Files imageDetails = new Uploaded_Files();

                    imageDetails.FileName = fileName;
                    imageDetails.ContentType = "image/jpeg";
                    imageDetails.DateCreated = DateTime.Now;
                    imageDetails.UserID = User.Identity.GetUserId();
                    imageDetails.FullPath = fullPath;

                    Stream imageStream = httpPostedFile.InputStream;
                    int imageLength = httpPostedFile.ContentLength;

                    byte[] image = new byte[imageLength];

                    imageStream.Read(image, 0, imageLength);

                    Image_Data imageObject = new Image_Data();
                    imageObject.Image_Data1 = image;

                    using (var context = new trackerEntities())
                    {
                        context.Image_Data.Add(imageObject);
                        context.SaveChanges();

                        imageDetails.MediaID = imageObject.ImageID;
                        context.Uploaded_Files.Add(imageDetails);
                        context.SaveChanges();
                    }

                    ReturnValue.Success = true;
                    ReturnValue.Message = "success";
                    ReturnValue.ID = imageDetails.ID;
                }
            }
            else
            {
                ReturnValue.Success = false;
                ReturnValue.Message = "Empty Request";
                ReturnValue.ID = 0;
            }
        }
        catch(Exception ex)
        {
            ReturnValue.Success = false;
            ReturnValue.Message = ex.Message;
            ReturnValue.ID = 0;
        }

        return ReturnValue;
    }

Xamarin应用程序Web请求:

代码语言:javascript
复制
public async Task<SimpleResponse> UploadImage(ImageUpload action)
    {
        SimpleResponse ReturnValue = new SimpleResponse();

        NSUserDefaults GlobalVar = NSUserDefaults.StandardUserDefaults;
        string token = GlobalVar.StringForKey("token");

        TaskCompletionSource<SimpleResponse> tcs = new TaskCompletionSource<SimpleResponse>();

        try
        {
            using (HttpClient httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
                httpClient.DefaultRequestHeaders.Add("Accept", "application/xml");

                using (var httpContent = new MultipartFormDataContent())
                {
                    ByteArrayContent baContent = new ByteArrayContent(action.Image.Data);
                    baContent.Headers.ContentType = new MediaTypeHeaderValue("Image/Jpeg");

                    string jsonString = JsonConvert.SerializeObject(action.UploadFiles);

                    StringContent stringContent = new StringContent(jsonString);
                    stringContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                    using (HttpResponseMessage httpResponse = await httpClient.PostAsync(new Uri("http://10.0.0.89/api/Location/UploadImage"), httpContent))
                    {
                        string returnData = httpResponse.Content.ReadAsStringAsync().Result;

                        SimpleResponse jsondoc = JsonConvert.DeserializeObject<SimpleResponse>(returnData);

                        ReturnValue.ID = jsondoc.ID;
                        ReturnValue.Message = jsondoc.Message;
                        ReturnValue.Success = jsondoc.Success;
                    }
                }
            }
        }
        catch(WebException ex)
        {
            ReturnValue.Success = false;

            if (ex.Status == WebExceptionStatus.Timeout)
            {
                ReturnValue.Message = "Request timed out.";
            }
            else
            {
                ReturnValue.Message = "Error";
            }

            tcs.SetResult(ReturnValue);
        }
        catch (Exception e)
        {
            ReturnValue.Success = false;
            ReturnValue.Message = "Something went wrong";
            tcs.SetResult(ReturnValue);
        }

        return ReturnValue;
    }
EN

回答 2

Stack Overflow用户

发布于 2018-01-23 19:44:15

在尝试发送内容之前,您没有将部件添加到内容中

代码语言:javascript
复制
//...code removed for brevity

httpContent.Add(baContent, "uploadedImage");
httpContent.Add(stringContent, "imageDetails");

//...send content

在服务器端,您可以检查以下答案

Http MultipartFormDataContent

关于如何读取传入的多部分请求

票数 0
EN

Stack Overflow用户

发布于 2018-01-24 19:46:28

代码语言:javascript
复制
try
   {
var jsonData = "{your json"}";
var content = new MultipartFormDataContent();

content.Add(new StringContent(jsonData.ToString()), "jsonData");
try
   {
     //Checking picture exists for upload or not using a bool variable
     if (isPicture)
       {
         content.Add(new StreamContent(_mediaFile.GetStream()), "\"file\"", $"\"{_mediaFile.Path}\"");
       }
     else
      {
         //If no picture for upload
         content.Add(new StreamContent(null), "file");
      }
   }
  catch (Exception exc)
   {
      System.Diagnostics.Debug.WriteLine("Exception:>" + exc);
   }

var httpClient = new HttpClient();
var response = await httpClient.PostAsync(new Uri("Your rest uri"), content);

 if (response.IsSuccessStatusCode)
 {
   //Do your stuff  
 } 
}
catch(Exception e)
 {
 System.Diagnostics.Debug.WriteLine("Exception:>" + e);
}

其中_mediaFile是从图库或相机中选择的文件。https://forums.xamarin.com/discussion/105805/photo-json-in-xamarin-post-webservice#latest

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48397588

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档