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); } }
public async Task<FileResult> UploadSingleFile(Guid id) { var uploadFolder = Path.Combine(Path.GetTempPath(), "EyeSoft.Prototype.Micro.Commanding", id.ToString()); Storage.Directory(uploadFolder).Create(); var streamProvider = new MultipartFormDataStreamProvider(uploadFolder); await Request.Content.ReadAsMultipartAsync(streamProvider); foreach (var file in streamProvider.FileData) { var fileName = file.Headers.ContentDisposition.FileName.Trim('\"'); fileName = Path.Combine(uploadFolder, fileName); var localFileName = Path.Combine(uploadFolder, file.LocalFileName); Storage.File(fileName).Directory.Create(); Storage.File(localFileName).MoveTo(fileName); } return new FileResult { FileNames = streamProvider.FileData.Select(entry => entry.LocalFileName), Names = streamProvider.FileData.Select(entry => entry.Headers.ContentDisposition.FileName), ContentTypes = streamProvider.FileData.Select(entry => entry.Headers.ContentType.MediaType), Description = streamProvider.FormData["description"], CreatedTimestamp = DateTime.UtcNow, UpdatedTimestamp = DateTime.UtcNow, }; }
// POST api/<controller> public async Task<HttpResponseMessage> Post(bool overwrite = false) { var tempPath = Path.GetTempPath(); var provider = new MultipartFormDataStreamProvider(tempPath); await this.Request.Content.ReadAsMultipartAsync(provider); foreach (var file in provider.FileData) { // アップロードファイル名の取得 var fileName = file.Headers.ContentDisposition.FileName; fileName = fileName.StartsWith("\"") || fileName.StartsWith("'") ? fileName.Substring(1, fileName.Length - 1) : fileName; fileName = fileName.EndsWith("\"") || fileName.EndsWith("'") ? fileName.Substring(0, fileName.Length - 1) : fileName; fileName = Path.GetFileName(fileName); // ファイルの移動 try { File.Move(file.LocalFileName, Path.Combine("D:\\", fileName)); } catch (Exception exception) { return this.Request.CreateResponse(HttpStatusCode.OK, new { Message = exception.Message }); } } return this.Request.CreateResponse(HttpStatusCode.OK); }
/// <summary> /// Accepts an Image from the tablet. /// </summary> /// <returns>Success</returns> public Task<HttpResponseMessage> PostImage(int HitchBotID = 10, string timeTaken = "20150121000000") { DateTime TimeTaken = DateTime.ParseExact(timeTaken, "yyyyMMddHHmmss", CultureInfo.InvariantCulture); HttpRequestMessage request = this.Request; if (!request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } string root = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/uploads/img"); var provider = new MultipartFormDataStreamProvider(root); var task = request.Content.ReadAsMultipartAsync(provider). ContinueWith<HttpResponseMessage>(o => { string file1 = provider.FileData.First().LocalFileName; // this is the file name on the server where the file was saved this should be passed on to upload it to azure Debug.WriteLine(file1); Helpers.AzureBlobHelper.UploadImageAndAddToDb(HitchBotID, TimeTaken, "", file1); return new HttpResponseMessage() { Content = new StringContent("File uploaded."), StatusCode = HttpStatusCode.OK }; } ); return task; }
public async Task<IList<string>> Post() { List<string> result = new List<string>(); if (Request.Content.IsMimeMultipartContent()) { try { MultipartFormDataStreamProvider stream = new MultipartFormDataStreamProvider(PATH); IEnumerable<HttpContent> bodyparts = await Request.Content.ReadAsMultipartAsync(stream); IDictionary<string, string> bodyPartFiles = stream.BodyPartFileNames; bodyPartFiles .Select(i => { return i.Value; }) .ToList() .ForEach(x => result.Add(x)); } catch (Exception e) { //log etc } } return result; }
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); } }
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); } }
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)); } }
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); }
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); } }
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); } }
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); } }
public HttpResponseMessage Post() { string requestBackupPath = Path.Combine(Environment.CurrentDirectory, "RequestZipFiles"); Console.WriteLine(requestBackupPath); MultipartFormDataStreamProvider streamProvider = new MultipartFormDataStreamProvider(requestBackupPath); return HttpContentMultipartExtensions.ReadAsMultipartAsync<MultipartFormDataStreamProvider>(this.Request.Content, streamProvider) .ContinueWith<HttpResponseMessage>((Func<Task<MultipartFormDataStreamProvider>, HttpResponseMessage>)(task => { //if any internal server error occurs during file read server error response will be sent if (task.IsFaulted || task.IsCanceled) { return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, (Exception)task.Exception); } var sourcePath = Enumerable.FirstOrDefault<string>( Enumerable.Select((IEnumerable<MultipartFileData>)streamProvider.FileData, (p => p.LocalFileName))); var deployRequestHandler = new DeployRequestHandler(); deployRequestHandler.Handle(new DeployRequestDto { SourcePath = sourcePath, DeployPath = "C:\\Test" }); return this.Request.CreateResponse(HttpStatusCode.OK, "Deployment is successfull"); })).Result; return this.Request.CreateResponse(HttpStatusCode.Created,"ok"); }
public 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); // Read the form data and return an async task. var task = Request.Content.ReadAsMultipartAsync(provider). ContinueWith<HttpResponseMessage>(t => { if (t.IsFaulted || t.IsCanceled) { Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception); } // 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); }); return task; }
public async Task<HttpResponseMessage> PostFile() { if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } EnsureBlobsFolder(blobsFolderPath); var provider = new MultipartFormDataStreamProvider(blobsFolderPath); try { await Request.Content.ReadAsMultipartAsync(provider); var entities = GenerateEntitiesAndRenameBlobs(provider).ToArray(); foreach (var entity in entities) { BlobStore.Save(entity); } return Request.CreateResponse(HttpStatusCode.OK, entities); } catch (System.Exception e) { return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e); } }
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; }
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()) }; } }
//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; }
public async Task<HttpResponseMessage> Post(string sessionKey, string channel) { string folderName = "_TemporaryFiles"; string PATH = HttpContext.Current.Server.MapPath("~/" + folderName); string rootUrl = Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.AbsolutePath, String.Empty); if (Request.Content.IsMimeMultipartContent()) { var streamProvider = new MultipartFormDataStreamProvider(PATH); //var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith<IEnumerable<FileDesc>>(t => //{ // //if (t.IsFaulted || t.IsCanceled) // //{ // // throw new HttpResponseException(HttpStatusCode.BadGateway); // //} // var fileInfo = streamProvider.FileData.Select(i => // { // var info = new FileInfo(i.LocalFileName); // return new FileDesc(info.Name, rootUrl+"/"+folderName+"/"+info.Name, info.Length); // }); // return fileInfo; //}); //return task; try { // Read the form data. await Request.Content.ReadAsMultipartAsync(streamProvider); Pubnub pubnub = new Pubnub("demo", "demo"); string pubnubChannel = channel; //var dbUser = unitOfWork.Users.All().FirstOrDefault(x => x.Sessionkey == sessionkey); var uploader = new DropboxUploader(); List<string> urls = new List<string>(); foreach (MultipartFileData file in streamProvider.FileData) { //Trace.WriteLine(file.Headers.ContentDisposition.FileName); //Trace.WriteLine("Server file path: " + file.LocalFileName); string fileName = file.LocalFileName.Normalize(); var url = uploader.UploadFileToDropBox(fileName.Trim(), file.Headers.ContentDisposition.FileName.Replace("\"", "")); urls.Add(url.ToString()); //dbUser.ProfilePicture = url; pubnub.Publish(pubnubChannel, url.ToString(), (object obj) => {}); //break; } return Request.CreateResponse(HttpStatusCode.OK, urls); } catch (System.Exception e) { return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e); } } else { throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted")); } }
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); } }
public Task<HttpResponseMessage> PostFile() { Thread.Sleep(5000); HttpRequestMessage request = this.Request; if (!request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType)); } string root = System.Web.HttpContext.Current.Server.MapPath("~/Dump"); var provider = new MultipartFormDataStreamProvider(root); var task = request.Content.ReadAsMultipartAsync(provider). ContinueWith<HttpResponseMessage>(o => { FileInfo finfo = new FileInfo(provider.FileData.First().LocalFileName); string guid = Guid.NewGuid().ToString(); File.Move(finfo.FullName, Path.Combine(root, guid + "_" + provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", ""))); return new HttpResponseMessage() { Content = new StringContent("File uploaded.") }; } ); return task; }
public async Task UploadWithUserName(string id) { if (!Request.Content.IsMimeMultipartContent("form-data")) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } MultipartFormDataStreamProvider streamProvider = new MultipartFormDataStreamProvider(Settings.Default.ServerUploadPath); await Request.Content.ReadAsMultipartAsync(streamProvider); MusicInfoImporter importer = new MusicInfoImporter(); foreach (MultipartFileData data in streamProvider.FileData) { string strFileName = data.Headers.ContentDisposition.FileName.Trim('"'); string strNewFileFullName = Settings.Default.ServerUploadPath + "\\" + Guid.NewGuid() + "_" + strFileName; File.Move(data.LocalFileName, strNewFileFullName); FileInfo fi = new FileInfo(strNewFileFullName); MusicInfo info = importer.ImportMusic(fi); if (info != null) { PlayRequest req = new PlayRequest() { MusicInfo = info, RequestDateTime = DateTime.Today, Username = id, PlayRequestType = PlayRequest.PlayRequestTypeEnum.Queue }; PlayRequestManager.SavePlayRequest(req); } } }
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); } }
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/uploads"); var provider = new MultipartFormDataStreamProvider(root); try { // Read the form data. await Request.Content.ReadAsMultipartAsync(provider); List<string> fileResultList = new List<string>(); // This illustrates how to get the file names. foreach (MultipartFileData file in provider.FileData) { if (file.Headers.ContentType.MediaType.Equals("text/xml")) { _xmlRepository.ProcessNewXml(file); fileResultList.Add("hello"); } } return Request.CreateResponse(HttpStatusCode.OK, fileResultList); } catch (System.Exception e) { return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e); } }
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"; }); }
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; }
public static async Task<MultipartFormInfo> ReadFile(this ApiController controller) { var Request = controller.Request; if (Request.Content.IsMimeMultipartContent()) { string root = HttpContext.Current.Server.MapPath("~/App_Data"); var provider = new MultipartFormDataStreamProvider(root); await Request.Content.ReadAsMultipartAsync(provider); var form = new MultipartFormInfo(); foreach (MultipartFileData file in provider.FileData) { var fileName = file.Headers.ContentDisposition.FileName; fileName = fileName.Replace("\"", ""); var mpi = new MultipartFileInfo() { RemoteFileName = fileName, FileInfo = new FileInfo(file.LocalFileName) }; form.Files.Add(mpi); } foreach (var key in provider.FormData.AllKeys) { form.FormData[key] = provider.FormData.GetValues(key); } return form; } return null; }
public async Task<IHttpActionResult> AddVideo() { if (!Request.Content.IsMimeMultipartContent()) { return BadRequest("Unsupported media type."); } string root = HttpContext.Current.Server.MapPath("~/App_Data"); var provider = new MultipartFormDataStreamProvider(root); await Request.Content.ReadAsMultipartAsync(provider); if (!provider.FileData.Any()) { return BadRequest("Image file needs to be uploaded"); } var file = provider.FileData.First(); try { var model = JsonConvert.DeserializeObject<AddVideoViewModel>(provider.FormData["model"]); var category = await _videoManager.GetVideoCategoryById(model.VideoCategoryId); if (category == null) { return BadRequest(); } var uniqueFilename = file.Headers.ContentDisposition.FileName.ToGfsFilename(); var sanitizedFilename = file.Headers.ContentDisposition.FileName.SanitizeWebApiContentDispositionFilename(); using (var fs = new FileStream(file.LocalFileName, FileMode.Open)) { await _gridFsHelper.UploadFromStreamAsync(uniqueFilename, fs, sanitizedFilename, MediaTypeEnum.Images); var video = new VideoFile { CategoryId = model.VideoCategoryId, CategoryName = category.Name, Name = model.VideoFilename, NameUrl = model.VideoFilename.Slugify(), YearReleased = model.YearReleased, Quality = model.Quality, ImageGfsFilename = uniqueFilename, ImageFilename = sanitizedFilename }; await _videoManager.AddVideoFile(video); } File.Delete(file.LocalFileName); return Ok(); } catch (Exception ex) { File.Delete(file.LocalFileName); Log.Error(ex); return InternalServerError(ex); } }
public async Task<Dictionary<string, string>> Post(int id = 0) { if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } Dictionary<string, string> dic = new Dictionary<string, string>(); 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);//获取上传文件在服务上默认的文件名 }//TODO:这样做直接就将文件存到了指定目录下,暂时不知道如何实现只接收文件数据流但并不保存至服务器的目录下,由开发自行指定如何存储,比如通过服务存到图片服务器 foreach (var key in provider.FormData.AllKeys) {//接收FormData dic.Add(key, provider.FormData[key]); } } catch { throw; } return dic; }
public async static Task<dynamic> CopyMulipartContent(ApiController controller) { if (!controller.Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } var root = HttpContext.Current.Server.MapPath("~/App_Data"); var provider = new MultipartFormDataStreamProvider(root); var tempPath = HttpContext.Current.Server.MapPath("~/Content/Temp/"); var fileNames = new List<string>(); await controller.Request.Content.ReadAsMultipartAsync(provider); foreach (MultipartFileData file in provider.FileData) { _fileId++; if (_fileId + 1 > Int32.MaxValue) _fileId = 0; var filename = tempPath + _fileId + "_" + file.Headers.ContentDisposition.FileName.Replace("\"", "").Replace("\\", ""); fileNames.Add(filename); File.Copy(file.LocalFileName, filename); FileHelper.WaitFileUnlockedAsync(() => File.Delete(file.LocalFileName), file.LocalFileName, 30, 800); } return new { formData = provider.FormData, fileNames }; }
public void GetStream() { Stream stream0 = null; Stream stream1 = null; try { string tempPath = Path.GetTempPath(); MultipartFormDataContent content = new MultipartFormDataContent(); content.Add(new StringContent("Content 1"), "NoFile"); content.Add(new StringContent("Content 2"), "File", "Filename"); MultipartFormDataStreamProvider provider = new MultipartFormDataStreamProvider(tempPath); stream0 = provider.GetStream(content, content.ElementAt(0).Headers); stream1 = provider.GetStream(content, content.ElementAt(1).Headers); Assert.IsType <MemoryStream>(stream0); Assert.IsType <FileStream>(stream1); Assert.Equal(1, provider.FileData.Count); string partialFileName = String.Format("{0}BodyPart_", tempPath); Assert.Contains(partialFileName, provider.FileData[0].LocalFileName); Assert.Same(content.ElementAt(1).Headers.ContentDisposition, provider.FileData[0].Headers.ContentDisposition); } finally { if (stream0 != null) { stream0.Close(); } if (stream1 != null) { stream1.Close(); } } }
public async Task PostProcessing_ProcessesFormData() { // Arrange int maxContents = 16; string contentFormat = "Content {0}"; string formNameFormat = "FormName_{0}"; MultipartFormDataContent multipartContent = new MultipartFormDataContent(); for (int index = 0; index < maxContents; index++) { string content = String.Format(contentFormat, index); string formName = String.Format(formNameFormat, index); multipartContent.Add(new StringContent(content), formName); } MultipartFormDataStreamProvider provider = new MultipartFormDataStreamProvider(ValidPath); foreach (HttpContent content in multipartContent) { provider.Contents.Add(content); provider.GetStream(multipartContent, content.Headers); } // Act await provider.ExecutePostProcessingAsync(); // Assert Assert.Equal(maxContents, provider.FormData.Count); for (int index = 0; index < maxContents; index++) { string content = String.Format(contentFormat, index); string formName = String.Format(formNameFormat, index); Assert.Equal(content, provider.FormData[formName]); } }
public void FormData_IsEmpty() { MultipartFormDataStreamProvider provider = new MultipartFormDataStreamProvider(ValidPath, ValidBufferSize); Assert.Empty(provider.FormData); }
public int MapFormData(System.Net.Http.MultipartFormDataStreamProvider provider) { string DocumentName = provider.FormData.GetValues("FileName").SingleOrDefault(); string DocumentType = provider.FormData.GetValues("TypeOfFile").SingleOrDefault(); string DocumentSize = provider.FormData.GetValues("FileSize").SingleOrDefault(); int DocumentTypeID = Convert.ToInt32(provider.FormData.GetValues("FileTypeID").SingleOrDefault()); int SupplierInvoiceID = Convert.ToInt32(provider.FormData.GetValues("InvoiceID").SingleOrDefault()); string PONumber = provider.FormData.GetValues("PONumber").SingleOrDefault(); if (DocumentTypeID == 0) { DocumentTypeID = docTypeService.GetDocTypeByName("Other"); } string data = provider.FormData.GetValues("File").SingleOrDefault(); var file = Convert.FromBase64String(data); //Post document to Alfresco var AlfrescoMetaData = alfService.Post(DocumentName, DocumentType, file, PONumber); //Get link ID and remove version string DocID = AlfrescoMetaData.Id; int index = DocID.LastIndexOf(";"); if (index > 0) { DocID = DocID.Substring(0, index); } //Save document metadata to ITS_Document if (AlfrescoMetaData != null) { try { ITS_Document objDocument = new ITS_Document(); objDocument.SupplierInvoiceID = SupplierInvoiceID; objDocument.DocumentTypeID = DocumentTypeID; objDocument.DocumentName = DocumentName; objDocument.DocumentType = DocumentType; objDocument.DocumentSize = DocumentSize; objDocument.EDMSID = DocID; objDocument.EDMSLocation = AlfrescoMetaData.Parents[0].Path; objDocument.EDMSName = DocumentName; //objDocument.EDMSLink = "http://dmssrv:8080/share/page/site/its/document-details?nodeRef=workspace://SpacesStore/" + DocID + ""; objDocument.EDMSLink = "http://dmssrv:8080/share/proxy/alfresco/slingshot/node/content/workspace/SpacesStore/" + DocID + "/" + DocumentName + ""; objDocument.DateCreated = System.DateTime.Now; objDocument.UserCreated = "Bongani"; objDocument.UserUpdated = 1; objDocument.DateUpdated = System.DateTime.Now; Add(objDocument); SaveChanges(); } catch (Exception e) { throw e as Exception; } return(SupplierInvoiceID); } return(SupplierInvoiceID); }
public void GetStreamThrowsOnNull() { MultipartFormDataStreamProvider instance = new MultipartFormDataStreamProvider(Path.GetTempPath()); Assert.ThrowsArgumentNull(() => { instance.GetStream(null); }, "headers"); }