猿问

如何使用 Xamarin 表单中的 POST 调用将文件对象发送到 Web api。?

我需要从我的 Xamarin 表单应用程序进行 POST 调用,我需要使用 POST 调用将文件对象上传到 API。有没有办法让它成为可能?



浮云间
浏览 191回答 2
2回答

吃鸡游戏

如果您使用 Base64 或 Byte[] 发送文件对象,那么它只允许限制可能高达 2-4 Mb,但如果您的图像比它更大,它将不支持。因此,解决方案是发布流内容,例如,var file = await CrossMedia.Current.PickPhotoAsync(new PickMediaOptions&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; PhotoSize = PhotoSize.Full,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; CompressionQuality = 100&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });创建类似MediaFile的对象,public MediaFile AttachedImage;并将文件存储到其中,这样内存流就不会丢失。喜欢,AttachedImage = fileAPI上的邮政编码,HttpClient httpClient = new HttpClient();MultipartFormDataContent mt = new MultipartFormDataContent();AttachedImage.GetStream().Position = 0;StreamContent imagePart = new StreamContent(AttachedImage.GetStream());imagePart.Headers.Add("Content-Type", ImageType);mt.Add(imagePart, String.Format("file"), String.Format("bk.jpeg"));requestMessage.Content = mt;var response = await httpClient.PostAsync("Your URL", mt);if (response.IsSuccessStatusCode){&nbsp; &nbsp; var responseString = await response.Content.ReadAsStringAsync();&nbsp; &nbsp; var objRootObjectuploadImage = JsonConvert.DeserializeObject<RootObjectuploadImage>(responseString);&nbsp; &nbsp; if (objRootObjectuploadImage != null)&nbsp; &nbsp; {&nbsp; &nbsp; }&nbsp; &nbsp; else&nbsp; &nbsp; {&nbsp; &nbsp; }}else{&nbsp; &nbsp; Loading(ActIndicator, false);&nbsp; &nbsp; await DisplayAlert(res.LAlert, "webserver not responding.", res.LOk);}

明月笑刀无情

不,不可能发送文件对象。您可以通过转换 Base64 字符串中的文件以 json 格式发送。这是建议的经过验证的解决方案。此链接包含用于从 Base64 来回转换的代码。
随时随地看视频慕课网APP
我要回答