本文整理汇总了C#中System.Net.Http.HttpContent.ReadAsMultipartAsync方法的典型用法代码示例。如果您正苦于以下问题:C# HttpContent.ReadAsMultipartAsync方法的具体用法?C# HttpContent.ReadAsMultipartAsync怎么用?C# HttpContent.ReadAsMultipartAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Http.HttpContent
的用法示例。
在下文中一共展示了HttpContent.ReadAsMultipartAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ReadFromStreamAsync
public override async Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
{
MultipartMemoryStreamProvider multipartMemoryStreamProvider = await content.ReadAsMultipartAsync();
Collection<HttpContent> contents = multipartMemoryStreamProvider.Contents;
ImageSet imageSet = await contents.FirstOrDefault<HttpContent>((HttpContent c) => c.Headers.ContentDisposition.Name.NormalizeName() == "imageset").ReadAsAsync<ImageSet>();
ImageSet images = imageSet;
Collection<HttpContent> httpContents = multipartMemoryStreamProvider.Contents;
List<HttpContent> list = (
from c in httpContents
where c.Headers.ContentDisposition.Name.NormalizeName().Matches("image\\d+")
select c).ToList<HttpContent>();
images.Images = new List<Image>();
foreach (HttpContent httpContent in list)
{
List<Image> images1 = images.Images;
Image image = new Image();
Image image1 = image;
image1.ImageData = await httpContent.ReadAsByteArrayAsync();
image.MimeType = httpContent.Headers.ContentType.MediaType;
image.FileName = httpContent.Headers.ContentDisposition.FileName.NormalizeName();
images1.Add(image);
images1 = null;
image1 = null;
image = null;
}
return images;
}
示例2: ReadFromStreamAsync
public async override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
{
if (!content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var Parts = await content.ReadAsMultipartAsync();
var FileContent = Parts.Contents.First(x =>
SupportedMediaTypes.Contains(x.Headers.ContentType));
var DataString = "";
foreach (var Part in Parts.Contents.Where(x => x.Headers.ContentDisposition.DispositionType == "form-data"
&& x.Headers.ContentDisposition.Name == "\"data\""))
{
var Data = await Part.ReadAsStringAsync();
DataString = Data;
}
string FileName = FileContent.Headers.ContentDisposition.FileName;
string MediaType = FileContent.Headers.ContentType.MediaType;
using (var Imgstream = await FileContent.ReadAsStreamAsync())
{
return new GenericContent { ContentType = MediaType, Body = ReadToEnd(Imgstream) };
}
}
示例3: ReadFromStreamAsync
public async override Task<object> ReadFromStreamAsync(Type type, Stream stream, HttpContent content, IFormatterLogger formatterLogger)
{
try
{
if (!content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var provider = await content.ReadAsMultipartAsync();
var mediacontent = provider.Contents.First(x =>
SupportedMediaTypes.Contains(x.Headers.ContentType));
string fileName = mediacontent.Headers.ContentDisposition.FileName;
string mediaType = mediacontent.Headers.ContentType.MediaType;
var imagebuffer = await mediacontent.ReadAsByteArrayAsync();
return new ImageMediaModels(fileName, mediaType, imagebuffer);
}
catch (Exception Ex)
{
string Err = "Unable to upload the image ";
Log.LogError("{0}, Error: {1}", Err, Ex.Message);
throw;
}
}
示例4: ReadFromStreamAsync
public async override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
{
var imageSet = new ImageSet();
var provider = await content.ReadAsMultipartAsync();
//extract model
var modelContent = provider.Contents.FirstOrDefault(c => c.Headers.ContentDisposition.Name.NormalizeName() == "imageset");
if (modelContent != null)
{
imageSet = await modelContent.ReadAsAsync<ImageSet>();
}
if (!imageSet.Images.Any())
{
//try extract from image content
var fileContents = provider.Contents.Where(c => c.Headers.ContentDisposition.Name.NormalizeName().Matches(@"image\d+")).ToList();
foreach (var fileContent in fileContents)
{
imageSet.Images.Add(new Image
{
FileName = fileContent.Headers.ContentDisposition.FileName.NormalizeName(),
MimeType = fileContent.Headers.ContentType.MediaType,
Side = GetSide(fileContent),
ImageData = await fileContent.ReadAsByteArrayAsync()
});
}
}
return imageSet;
}
示例5: ReadFromStreamAsync
public override async Task<object> ReadFromStreamAsync(Type type, Stream stream,
HttpContent httpContent,
IFormatterLogger iFormatterLogger)
{
MultipartStreamProvider parts = await httpContent.ReadAsMultipartAsync();
IEnumerable<HttpContent> contents = parts.Contents;
HttpContent content = contents.FirstOrDefault();
foreach (HttpContent c in contents ) {
if (SupportedMediaTypes.Contains(c.Headers.ContentType)) {
content = c;
break;
}
}
using (var msgStream = await content.ReadAsStreamAsync())
{
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(TenMsg));
TenMsg msg = (TenMsg)js.ReadObject(msgStream);
Debug.WriteLine("msgString: " + msgStream.ToString());
int sender = msg.Sender;
int receiver = msg.Receiver;
byte phoneType = msg.PhoneType;
bool isLocked = msg.IsLocked;
DateTime msgTime = msg.MsgTime;
string msgContent = msg.MsgContent;
Debug.WriteLine("Msg Content: " + msg.MsgContent);
return new TenMsg(sender, receiver, phoneType, isLocked, msgTime, msgContent);
}
}
示例6: UploadFileAsync
public async Task<string> UploadFileAsync(HttpContent httpContent)
{
var provider = new LocalStorageServiceProvider(_path);
await httpContent.ReadAsMultipartAsync(provider);
var fileData = provider.FileData.First();
return Path.GetFileName(fileData.LocalFileName);
}
示例7: SaveFilesTemporarily
public static async Task<MultipartFormDataStreamProvider> SaveFilesTemporarily(HttpContent content)
{
TryToCreateDirectory(DEFAULT_TEMPORARY);
// Transfer data to temporary location.
var provider = new MultipartFormDataStreamProvider(ContextualizedPath(DEFAULT_DIRECTORY, DEFAULT_TEMPORARY));
await content.ReadAsMultipartAsync(provider);
return provider;
}
示例8: ReadMultipart
static async Task<Document> ReadMultipart(DatabaseApi couchApi, HttpContent content)
{
var multipart = (await content.ReadAsMultipartAsync()).ToArray();
var jsonPart = multipart.FirstOrDefault(
part => part.Headers.ContentType != null && part.Headers.ContentType.MediaType == MediaType.Json);
if (jsonPart == null)
return null;
var document = ReadDocument(
couchApi, await jsonPart.ReadAsUtf8TextReaderAsync());
PrefillAttachmentDataGetters(multipart, document);
return document;
}
示例9: GetModel
/// <summary>
/// Builds the model from the request contents
/// </summary>
/// <param name="content"></param>
/// <param name="provider"></param>
/// <returns></returns>
private async Task<ContentItemSave> GetModel(HttpContent content, MultipartFormDataStreamProvider provider)
{
var result = await content.ReadAsMultipartAsync(provider);
if (result.FormData["contentItem"] == null)
{
throw new HttpResponseException(
new HttpResponseMessage(HttpStatusCode.BadRequest)
{
ReasonPhrase = "The request was not formatted correctly and is missing the 'contentItem' parameter"
});
}
//get the string json from the request
var contentItem = result.FormData["contentItem"];
//transform the json into an object
var model = JsonConvert.DeserializeObject<ContentItemSave>(contentItem);
//get the files
foreach (var file in result.FileData)
{
var parts = file.Headers.ContentDisposition.Name.Trim(new char[] {'\"'}).Split('_');
if (parts.Length != 2)
{
throw new HttpResponseException(
new HttpResponseMessage(HttpStatusCode.BadRequest)
{
ReasonPhrase = "The request was not formatted correctly the file name's must be underscore delimited"
});
}
int propertyId;
if (!int.TryParse(parts[1], out propertyId))
{
throw new HttpResponseException(
new HttpResponseMessage(HttpStatusCode.BadRequest)
{
ReasonPhrase = "The request was not formatted correctly the file name's 2nd part must be an integer"
});
}
model.UploadedFiles.Add(new ContentItemFile
{
FilePath = file.LocalFileName,
PropertyId = propertyId
});
}
return model;
}
示例10: Convert
public async Task<FormData> Convert(HttpContent content)
{
if(content == null)
throw new ArgumentNullException("content");
if (!content.IsMimeMultipartContent())
{
throw new Exception("Unsupported Media Type");
}
MultipartMemoryStreamProvider multipartProvider = await content.ReadAsMultipartAsync();
var multipartFormData = await Convert(multipartProvider);
return multipartFormData;
}
示例11: ReadFromStreamAsync
public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
{
if (!content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var taskCompletionSource = new TaskCompletionSource<object>();
content.ReadAsMultipartAsync().ContinueWith(t =>
{
if (t.IsFaulted || t.IsCanceled)
throw new HttpResponseException(HttpStatusCode.InternalServerError);
var fileContents = t.Result.Contents.Where(x => SupportedMediaTypes.Contains(x.Headers.ContentType))
.ToArray();
if (!fileContents.Any())
{
taskCompletionSource.SetResult(null);
}
else
{
var fileMedias = new List<FileMedia>();
foreach (var fileContent in fileContents)
{
var fileName = fileContent.Headers.ContentDisposition.FileName;
var mediaType = fileContent.Headers.ContentType.MediaType;
using (var imgStream = fileContent.ReadAsStreamAsync().Result)
{
var imageBuffer = imgStream.ReadFully();
var result = new FileMedia(fileName, mediaType, imageBuffer);
fileMedias.Add(result);
}
}
if (fileMedias.Count == 1)
{
taskCompletionSource.SetResult(fileMedias.Single());
}
else
{
taskCompletionSource.SetResult(fileMedias);
}
}
});
return taskCompletionSource.Task;
}
示例12: ReadFromStreamAsync
/// <summary>
/// Reads input stream as ProjectModel class.
/// </summary>
/// <param name="type">Target type.</param>
/// <param name="readStream">Input stream.</param>
/// <param name="content"></param>
/// <param name="formatterLogger"></param>
/// <returns></returns>
public override async Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
{
var provider = new MultipartFormDataStreamProvider(_uploadPath);
try
{
await content.ReadAsMultipartAsync(provider);
}
catch (Exception e)
{
Trace.TraceInformation("Failed multipart message reading: {0}", e);
return null;
}
return _multipartForm.GetModel(type, new FormDataProvider(provider, formatterLogger));
}
示例13: ReadFromStreamAsync
public override async Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content,
IFormatterLogger formatterLogger)
{
var parts = await content.ReadAsMultipartAsync();
var obj = Activator.CreateInstance(type);
var propertiesFromObj = obj.GetType().GetRuntimeProperties().ToList();
foreach (var property in propertiesFromObj.Where(x => x.PropertyType == typeof(ContentModel)))
{
var file = parts.Contents.FirstOrDefault(x => x.Headers.ContentDisposition.Name.Contains(property.Name));
if (file == null || file.Headers.ContentLength <= 0) continue;
try
{
var fileModel = new ContentModel(file.Headers.ContentDisposition.FileName,
Convert.ToInt32(file.Headers.ContentLength), ReadFully(file.ReadAsStreamAsync().Result));
property.SetValue(obj, fileModel);
}
catch (Exception e)
{
}
}
foreach (var property in propertiesFromObj.Where(x => x.PropertyType != typeof(ContentModel)))
{
var formData =
parts.Contents.FirstOrDefault(x => x.Headers.ContentDisposition.Name.Contains(property.Name));
if (formData == null) continue;
try
{
var strValue = formData.ReadAsStringAsync().Result;
var valueType = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
var value = Convert.ChangeType(strValue, valueType);
property.SetValue(obj, value);
}
catch (Exception e)
{
}
}
return obj;
}
示例14: UploadBlobs
public async Task<List<BlobUploadModel>> UploadBlobs(HttpContent httpContent)
{
var blobUploadProvider = new BlobStorageUploadProvider();
var list = await httpContent.ReadAsMultipartAsync(blobUploadProvider)
.ContinueWith(task =>
{
if (task.IsFaulted || task.IsCanceled)
{
throw task.Exception;
}
var provider = task.Result;
return provider.Uploads.ToList();
});
return list; // devuelvo el modelo de la imagen subida al azure
}
示例15: UploadBlob
public async Task<FileUploadModel> UploadBlob(HttpContent httpContent, string filterPropertyName, IEnumerable<string> supportedFileTypes = null)
{
var MultiPartProvider = new MultipartFormDataStreamProvider(Path.GetTempPath());
await httpContent.ReadAsMultipartAsync(MultiPartProvider).ContinueWith(task =>
{
if (task.IsFaulted || task.IsCanceled)
{
throw task.Exception;
}
});
var fileData = MultiPartProvider.FileData.FirstOrDefault(x => x.Headers.ContentDisposition.Name == string.Concat("\"", filterPropertyName, "\""));
var blobContainer = BlobHelper.GetBlobContainer();
if (fileData == null) return null;
return await UploadOneToBlob(blobContainer, fileData, supportedFileTypes);
}