我已经使用formdata将文本文件发布到web web api的action方法中。当我发送文本文件时,它工作正常,但是当我发送图像文件或视频文件或音频文件时,它无法正常工作。
电话会议:
using (var client = new HttpClient())
{
using (var formData = new MultipartFormDataContent())
{
HttpContent fileStreamContent = new StreamContent(new MemoryStream(fileStream));
formData.Add(fileStreamContent, "fileForUpload");
using (var response = await client.PostAsync("http://localhost:56537/api/CreateContainer/UploadBlobs", formData))
{
if (response.IsSuccessStatusCode)
{
var productJsonString = await response.Content.ReadAsStringAsync();
}
}
}
}
在行动方法:
try
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
var file = provider.Contents[0];
objAzureFunctionClass.UploadBlobsToContainer(file.ReadAsStringAsync().Result, filenametoUpload, containerNametoUpload);
return false;
}
public bool UploadBlobsToContainer(string fileStream, string filenametoUpload, string containerNametoUpload)
{
try
{
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference(containerNametoUpload);
CloudBlockBlob blockBlob = container.GetBlockBlobReference(filenametoUpload);
blockBlob.UploadFromStream(GenerateStreamFromString(fileStream));
return true;
}
catch (Exception ex)
{
throw ex;
}
}
private Stream GenerateStreamFromString(String p)
{
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(p);
writer.Flush();
stream.Position = 0;
return stream;
}