当前位置: 首页>>代码示例>>C#>>正文


C# Http.MultipartFormDataStreamProvider类代码示例

本文整理汇总了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);
            }
        }
开发者ID:justinconnell,项目名称:remi,代码行数:31,代码来源:UploadController.cs

示例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())
         };
     }
 }
开发者ID:pmhsfelix,项目名称:WcfWebApi.Preview5.Explorations,代码行数:29,代码来源:MultiPartRequest.cs

示例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);
            }
        }
开发者ID:ehsmohammadi,项目名称:BTE.RMS,代码行数:34,代码来源:MeetingFilesController.cs

示例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;
 }
开发者ID:hbkzqp,项目名称:BibleStudy,代码行数:8,代码来源:BibleUpdateController.cs

示例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;
        }
开发者ID:hmaddi,项目名称:Inventory,代码行数:60,代码来源:FileUploadController.cs

示例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";
                                                 });
        }
开发者ID:mamluka,项目名称:SpeedyMailer,代码行数:26,代码来源:ListsController.cs

示例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);
            }
        }
开发者ID:rasikag,项目名称:SubtitleProject,代码行数:29,代码来源:FileUploadController.cs

示例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);
            }
        }
开发者ID:codercamps,项目名称:FullStackNET,代码行数:29,代码来源:UploadController.cs

示例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);
            }
        }
开发者ID:ViktoryiaR,项目名称:TicketSellingSystem,代码行数:26,代码来源:AdminCinemaController.cs

示例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);
        }
开发者ID:JoshuaSlaven42,项目名称:resume,代码行数:31,代码来源:UserFileController.cs

示例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));
            }
        }
开发者ID:Chitva,项目名称:Ganjine,代码行数:25,代码来源:ResumableController.cs

示例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);
            }
        }
开发者ID:asanjeevak,项目名称:Windays2015,代码行数:25,代码来源:VideoStreamController.cs

示例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);
     }
 }
开发者ID:tmonte,项目名称:iap-api,代码行数:30,代码来源:ImagesController.cs

示例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);
            }
        }
开发者ID:vgoloviznin,项目名称:test-upload,代码行数:34,代码来源:UploadController.cs

示例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;
        }
开发者ID:jakobloekke,项目名称:Belle,代码行数:27,代码来源:ContentItemBinder.cs


注:本文中的System.Net.Http.MultipartFormDataStreamProvider类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。