0
下面的代碼負責上傳圖片:贏手機8/ASP的.NET Web API圖片上傳
[HttpPost]
public async Task<HttpResponseMessage> Upload()
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var streamProvider = new MultipartMemoryStreamProvider();
Cloudinary cloudinary = new Cloudinary(ConfigurationManager.AppSettings.Get("CLOUDINARY_URL"));
return await Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(t =>
{
if (t.IsFaulted || t.IsCanceled)
throw new HttpResponseException(HttpStatusCode.InternalServerError);
var content = streamProvider.Contents.FirstOrDefault().ReadAsStreamAsync();
ImageUploadParams uploadParams = new ImageUploadParams()
{
File = new CloudinaryDotNet.Actions.FileDescription(Guid.NewGuid().ToString(), content.Result)
};
ImageUploadResult uploadResult = cloudinary.Upload(uploadParams);
string url = cloudinary.Api.UrlImgUp.BuildUrl(String.Format("{0}.{1}", uploadResult.PublicId, uploadResult.Format));
return Request.CreateResponse<MediaModel>(HttpStatusCode.Created, new MediaModel { URL = url });
});
}
它通過jQuery POST請求的工作。但是,在win phone 8應用程序中,以下代碼似乎沒有向api發出請求:
public async Task<string> UploadImage(byte[] image)
{
var client = new HttpClient();
var content = new MultipartFormDataContent();
var imageContent = new ByteArrayContent(image);
imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/jpeg");
content.Add(imageContent, "image", string.Format("{0}.jpg", Guid.NewGuid().ToString()));
return await client.PostAsync(baseURL + "image/Upload", content).Result.Content.ReadAsStringAsync().ContinueWith(t =>
{
return t.Result;
});
}
這裏有什麼問題?我希望有人能告訴我正確使用httpclient。
您收到的錯誤消息是什麼? – tugberk
它不會拋出任何異常。應用程序不能向api發出請求,但其他api方法(例如Get方法)正常工作。 – onatm