本文整理汇总了C#中System.Net.Http.MultipartFormDataStreamProvider类的典型用法代码示例。如果您正苦于以下问题:C# MultipartFormDataStreamProvider类的具体用法?C# MultipartFormDataStreamProvider怎么用?C# MultipartFormDataStreamProvider使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
MultipartFormDataStreamProvider类属于System.Net.Http命名空间,在下文中一共展示了MultipartFormDataStreamProvider类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Post
public async Task<HttpResponseMessage> Post()
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
Logger.InfoFormat("Files for upload received.");
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
try
{
await Request.Content.ReadAsMultipartAsync(provider);
var items = new List<dynamic>();
foreach (MultipartFileData file in provider.FileData)
{
items.Add(new { name = Path.GetFileName(file.LocalFileName), size = new FileInfo(file.LocalFileName).Length });
}
Logger.InfoFormat("Uploaded files: {0}", Serialization.ToJson(items));
return Request.CreateResponse(HttpStatusCode.OK, items);
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
示例2: Post
HttpResponseMessage Post(HttpRequestMessage req)
{
try
{
if (!req.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var prov = new MultipartFormDataStreamProvider("c:/users/pedro/data/tmp");
req.Content.ReadAsMultipart(prov);
var sb = new StringBuilder("Files uploaded\n");
foreach (var me in prov.BodyPartFileNames)
{
sb.AppendFormat("{0}->{1};\n ", me.Key, me.Value);
}
return new HttpResponseMessage
{
Content = new StringContent(sb.ToString())
};
}
catch (Exception e)
{
Console.WriteLine(e);
return new HttpResponseMessage
{
Content = new StringContent(e.ToString())
};
}
}
示例3: PostFormData
public async Task<HttpResponseMessage> PostFormData(long meetingId)
{
//Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
var files = new List<FileDto>();
try
{
// Read the form data.
await Request.Content.ReadAsMultipartAsync(provider);
// This illustrates how to get the file names.
foreach (var file in provider.FileData)
{
files.Add(new FileDto
{
ContentType = file.Headers.ContentType.MediaType,
Content = Convert.ToBase64String(File.ReadAllBytes(file.LocalFileName))
});
}
//meetingService.AddFiles(meetingId, Guid.Empty,files);
return Request.CreateResponse(HttpStatusCode.OK);
}
catch (Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
示例4: Get
//GET: api/Bible/5
public int Get()
{
string root = HttpContext.Current.Server.MapPath("~/Resource/Images");
var provider = new MultipartFormDataStreamProvider(root);
Request.Content.ReadAsMultipartAsync(provider);
return 0;
}
示例5: UploadFile
public async Task<FileResult> UploadFile()
{
string uploadFolder = WebConfigurationManager.AppSettings["Source"];
// Verify that this is an HTML Form file upload request
if (!Request.Content.IsMimeMultipartContent("form-data"))
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType));
}
// Create a stream provider for setting up output streams
MultipartFormDataStreamProvider streamProvider = new MultipartFormDataStreamProvider(uploadFolder);
// Read the MIME multipart asynchronously content using the stream provider we just created.
await Request.Content.ReadAsMultipartAsync(streamProvider);
string localfileName = streamProvider.FileData.Select(entry => entry.LocalFileName).FirstOrDefault();
string filename = HttpContext.Current.Request.QueryString["filename"];
string uploadType = "inventory";
uploadType = HttpContext.Current.Request.QueryString["uploadtype"];
LoggingManager.Instance.GetLogger.InfoFormat("uploadType:====>{1}<==== FileName: ====>{0}<====", filename, uploadType);
FileResult result = new FileResult();
if (string.IsNullOrEmpty(filename))
{
LoggingManager.Instance.GetLogger.Error("Submitted File Name does not exist..Aborting.");
result.Success = "Failure";
}
else
{
try
{
if (string.IsNullOrEmpty(localfileName))
{
throw new ArgumentNullException();
}
switch (uploadType)
{
case "inventory":
ProcessInventoryFile(localfileName, filename);
break;
case "cluster":
break;
case "activedirectory":
ProcessActivedirectoryFile(localfileName, filename);
break;
default:
throw new NotSupportedException("Upload Type is not supported");
}
result.Success = "Success";
}
catch (Exception ex)
{
LoggingManager.Instance.GetLogger.Error("Fatal exception thrown while processing file. Aborting...", ex);
result.Success = "Failure";
}
}
return result;
}
示例6: Upload
public Task<string> Upload()
{
if (!Request.Content.IsMimeMultipartContent())
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
var provider = new MultipartFormDataStreamProvider(HostingEnvironment.ApplicationPhysicalPath);
var task = Request.Content.ReadAsMultipartAsync(provider);
return task.ContinueWith(t =>
{
var file = t.Result.FileData.Select(x => x.LocalFileName).FirstOrDefault();
if (file == null)
throw new HttpRequestException("the file was not uploaded correctly");
_api
.AddFiles(new[] { file })
.Call<ServiceEndpoints.Lists.UploadContacts>(x =>
{
x.ListId = t.Result.FormData["listId"];
});
return "OK";
});
}
示例7: PostFormData
public async Task<HttpResponseMessage> PostFormData()
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
try
{
// Read the form data.
await Request.Content.ReadAsMultipartAsync(provider);
// This illustrates how to get the file names.
foreach (MultipartFileData file in provider.FileData)
{
Trace.WriteLine(file.Headers.ContentDisposition.FileName);
Trace.WriteLine("Server file path: " + file.LocalFileName);
}
return Request.CreateResponse(HttpStatusCode.OK);
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
示例8: PostFile
public async Task<IHttpActionResult> PostFile()
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent()) {
return StatusCode(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
try {
StringBuilder sb = new StringBuilder(); // Holds the response body
// Read the form data and return an async task.
await Request.Content.ReadAsMultipartAsync(provider);
// This illustrates how to get the file names for uploaded files.
foreach (var file in provider.FileData) {
var fileName = file.Headers.ContentDisposition.FileName;
var fileMimeType = file.Headers.ContentType;
FileInfo fileInfo = new FileInfo(file.LocalFileName);
sb.Append(string.Format("Uploaded file {0} of type {1} to {2} ({3} bytes)\n", fileName, fileMimeType, fileInfo.Name, fileInfo.Length));
}
return Ok(sb.ToString());
}
catch (System.Exception e) {
return InternalServerError(e);
}
}
示例9: UploadPhoto
public async Task<HttpResponseMessage> UploadPhoto([FromBody] int filmId)
{
string[] extensions = { ".jpg", ".jpeg", ".gif", ".bmp", ".png" };
try
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var root = HttpContext.Current.Server.MapPath("~/Content/Images");
var provider = new MultipartFormDataStreamProvider(root);
await Request.Content.ReadAsMultipartAsync(provider);
var filePath = provider.FileData.First().LocalFileName;
if (!extensions.Any(x =>
x.Equals(Path.GetExtension(filePath.ToLower()),
StringComparison.OrdinalIgnoreCase)))
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
// _service.SavePhoto(filmId, filePath);
return Request.CreateResponse(HttpStatusCode.OK);
}
catch (Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
示例10: PostUserFile
public async Task<IHttpActionResult> PostUserFile()
{
HttpRequestMessage request = this.Request;
if (!request.Content.IsMimeMultipartContent())
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
var root = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/userfiles");
var provider = new MultipartFormDataStreamProvider(root);
await request.Content.ReadAsMultipartAsync(provider);
var data = provider.FileData.FirstOrDefault();
var fileName = data.Headers.ContentDisposition.FileName;
if(string.IsNullOrEmpty(fileName))
throw new HttpResponseException(HttpStatusCode.NotAcceptable);
var fileInfo = new FileInfo(data.LocalFileName);
var record = new UserFile()
{
FileName = fileName,
LocalFileName = fileInfo.Name,
ContentType = data.Headers.ContentType.ToString(),
FileGuid = Guid.NewGuid(),
OwnerIdentity = User.Identity.Name
};
db.Save(record);
return Ok(record);
}
示例11: Upload
public async Task<object> Upload()
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
if (!Directory.Exists(root)) Directory.CreateDirectory(root);
var provider = new MultipartFormDataStreamProvider(root);
if (await readPart(provider))
{
// Success
return Request.CreateResponse(HttpStatusCode.OK);
}
else
{
// Fail
var message = DeleteInvalidChunkData(provider) ?
"Cannot read multi part file data." :
"Cannot delete temporary file chunk data.";
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError,
new System.Exception(message));
}
}
示例12: UploadFilesFromBrowser
public async Task<HttpResponseMessage> UploadFilesFromBrowser()
{
if (Request.Content.IsMimeMultipartContent())
{
string path = HttpContext.Current.Server.MapPath("~");
string imagePath = Path.Combine(path, @"Files\");
var streamProvider = new MultipartFormDataStreamProvider(imagePath);
await Request.Content.ReadAsMultipartAsync(streamProvider);
foreach (var file in streamProvider.FileData)
{
string newFileName = Path.Combine(imagePath, Guid.NewGuid().ToString() + ".jpg");
File.Move(file.LocalFileName, newFileName);
}
var response = Request.CreateResponse(HttpStatusCode.Accepted, "Good work, sir!");
return response;
}
else
{
return Request.CreateResponse(HttpStatusCode.NotAcceptable);
}
}
示例13: Upload
public async Task<IHttpActionResult> Upload()
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
try
{
await Request.Content.ReadAsMultipartAsync(provider);
List<Image> images = new List<Image>();
foreach (MultipartFileData file in provider.FileData)
{
Trace.WriteLine(file.Headers.ContentDisposition.FileName);
Trace.WriteLine("Server file path: " + file.LocalFileName);
var batchId = Convert.ToInt16(provider.FormData.Get(0));
var fileName = Path.GetFileName(file.LocalFileName);
var image = new Image { BatchID = batchId, FileName = fileName };
db.Images.Add(image);
images.Add(image);
}
db.SaveChanges();
return Ok(images);
}
catch (Exception e)
{
return BadRequest(e.Message);
}
}
示例14: Post
public async Task<HttpResponseMessage> Post()
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
const string fileDirectory = "UploadedFiles/";
string root = HttpContext.Current.Server.MapPath("~/" + fileDirectory);
var provider = new MultipartFormDataStreamProvider(root);
try
{
await Request.Content.ReadAsMultipartAsync(provider);
var filepath = "";
foreach (var file in provider.FileData)
{
var filename = Guid.NewGuid() + file.Headers.ContentDisposition.FileName.Replace("\"", "");
var fileInfo = new FileInfo(file.LocalFileName);
File.Move(fileInfo.FullName, root + filename);
}
return new HttpResponseMessage
{
Content = new StringContent(filepath)
};
}
catch (Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
示例15: BindModel
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
//NOTE: Validation is done in the filter
if (!actionContext.Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var root = HttpContext.Current.Server.MapPath("~/App_Data/TEMP/FileUploads");
//ensure it exists
Directory.CreateDirectory(root);
var provider = new MultipartFormDataStreamProvider(root);
var task = Task.Run(() => GetModel(actionContext.Request.Content, provider))
.ContinueWith(x =>
{
if (x.IsFaulted && x.Exception != null)
{
throw x.Exception;
}
bindingContext.Model = x.Result;
});
task.Wait();
return bindingContext.Model != null;
}