public IHttpActionResult Post([FromBody] ProfileUpdateVM profile)
        {
#if OFF
    // http://stackoverflow.com/questions/10320232/how-to-accept-a-file-post-asp-net-mvc-4-webapi
            if (Request.Content.IsMimeMultipartContent())
            {
                var provider = new MultipartMemoryStreamProvider();
                Request.Content.ReadAsMultipartAsync(provider);
                foreach (HttpContent file in provider.Contents)
                {
                    string filename = file.Headers.ContentDisposition.FileName.Trim('\"');
                    byte[] buffer = file.ReadAsByteArrayAsync().Result;

                    string filePath = HttpContext.Current.Server.MapPath("~/" + filename);

                    using (var sw = new StreamWriter(filePath))
                    {
                        sw.Write(buffer);
                    }
                }
            }
#endif

            bool ret = _appUserRepo.UpdateProfile(profile);
            return Ok(ret);
        }
Beispiel #2
0
        public async Task<IHttpActionResult> uploadPicture()
        {
            if (Request.Content.IsMimeMultipartContent())
            {
                var streamProvider = new MultipartMemoryStreamProvider();
                streamProvider = await Request.Content.ReadAsMultipartAsync(streamProvider);


               var item = streamProvider.Contents.Where(c => !string.IsNullOrEmpty(c.Headers.ContentDisposition.FileName)).First();
                
                Stream stPicture = new MemoryStream(await item.ReadAsByteArrayAsync());

                WeedCSharpClientProxy weedProxy = new WeedCSharpClientProxy();
               var result = weedProxy.Upload(stPicture);

                var index = result.url.LastIndexOf('/') + 1;
                var fid = result.url.Substring(index);

                var tempUser = PostsLogic.postContext.AspNetUsers.First(u => u.Id == User.Identity.GetUserId());
             //   tempUser.ProfilePicture = fid;
                PostsLogic.postContext.SubmitChanges();
                return Ok(fid);
            }

            return BadRequest();
        }
        public virtual async Task<IHttpActionResult> UploadFile()
        {
            if (!Request.Content.IsMimeMultipartContent())
                throw new Exception();
            var provider = new MultipartMemoryStreamProvider();
            await Request.Content.ReadAsMultipartAsync(provider);
            var fileInfo = new FileDataContract {UserName = User.Identity.Name};
            Stream buffer = null;
            foreach (var content in provider.Contents)
            {
                var name = content.Headers.ContentDisposition.Name.Trim('\"');
                if (string.Equals(name, "referenceNotes", StringComparison.InvariantCultureIgnoreCase))
                {
                    fileInfo.ReferenceNotes = await content.ReadAsStringAsync();
                    continue;
                }
                if (string.Equals(name, "fileHandler", StringComparison.InvariantCultureIgnoreCase))
                {
                    fileInfo.HandlerName = await content.ReadAsStringAsync();
                    continue;
                }
                if (string.Equals(name, "mediaType", StringComparison.InvariantCultureIgnoreCase))
                {
                    fileInfo.MediaType = await content.ReadAsStringAsync();
                    continue;
                }
                if (!string.Equals(name, "file", StringComparison.InvariantCultureIgnoreCase)) continue;
                fileInfo.OriginalFileName = content.Headers.ContentDisposition.FileName.Trim('\"');
                buffer = await content.ReadAsStreamAsync();
            }
            var result = await service.UpsertFileDataSource(fileInfo, buffer);

            return Ok(result);
        }
        public virtual async Task<HttpResponseMessage> Post()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                return new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType);
            }

            var provider = new MultipartMemoryStreamProvider();
            await this.Request.Content.ReadAsMultipartAsync(provider);

            var ids = new List<string>(provider.Contents.Count);
            foreach (var file in provider.Contents)
            {
                var bytes = await file.ReadAsByteArrayAsync();

                var id = await this.preprocessor.Process(bytes, file.Headers.ContentType.MediaType, file.Headers.ContentDisposition.FileName.Trim('\"'));

                ids.Add(id);
            }

            return new HttpResponseMessage(HttpStatusCode.Created)
            {
                Content = new StringContent(JsonConvert.SerializeObject(ids), Encoding.UTF8, "application/json"),
            };
        }
        public async Task<IHttpActionResult> Post()
        {
            var image = new UploadImage();
            try
            {
                var provider = new MultipartMemoryStreamProvider();

                await Request.Content.ReadAsMultipartAsync(provider);

                foreach (var file in provider.Contents)
                {
                    // Seems kind of hackish as a method for determining where the file name is in the content stream
                    if (file.Headers.ContentDisposition.FileName != null)
                    {
                        // Get file specifics and save 
                        image.fileName = file.Headers.ContentDisposition.FileName.Trim('\"');
                        image.file = await file.ReadAsByteArrayAsync();

                        image = await this.processor.SaveAndResizeImage(image);
                    }
                }

            }
            catch (Exception exception)
            {
                return InternalServerError(exception);
            }
            // Technically we could return the upload image json if we needed that client side
            return Ok(image.file);
        }
Beispiel #6
0
        public void ReadAsMultipartAsync_ParsesEmptyContent(string boundary)
        {
            HttpContent content = CreateContent(boundary);
            MultipartMemoryStreamProvider result = content.ReadAsMultipartAsync().Result;

            Assert.Empty(result.Contents);
        }
 public Task<HttpResponseMessage> Post()
 {
     if (Request.Content.IsMimeMultipartContent()) {
         var streamProvider = new MultipartMemoryStreamProvider();
         var task = Request.Content
             .ReadAsMultipartAsync(streamProvider)
             .ContinueWith<HttpResponseMessage>(t => {
                 if (t.IsFaulted || t.IsCanceled) {
                     throw new HttpResponseException(HttpStatusCode.InternalServerError);
                 }
                 foreach (var item in streamProvider.Contents) {
                     var getContentTask = item.ReadAsStreamAsync();
                     var csvReader = new CsvReader(new StreamReader(getContentTask.Result));
                     csvReader.Configuration.CultureInfo = CultureInfo.CurrentCulture;
                     csvReader.Configuration.Delimiter = CultureInfo.CurrentCulture.TextInfo.ListSeparator;
                     csvReader.Configuration.RegisterClassMap<ReadingMap>();
                     while (csvReader.Read()) {
                         Debug.WriteLine(csvReader.GetRecord<Reading>());
                     }
                 }
                 return Request.CreateResponse(HttpStatusCode.OK, new {
                     Result = "OK"
                 });
             });
         return task;
     } else {
         throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
     }
 }
Beispiel #8
0
        public async Task<HttpResponseMessage> Upload()
        {

            var streamProvider = new MultipartMemoryStreamProvider();
            await Request.Content.ReadAsMultipartAsync(streamProvider);
            var fileNames = new List<string>();
            foreach (var item in streamProvider.Contents)
            {
                if (item.Headers.ContentDisposition.FileName != null)
                {
                    var ms = item.ReadAsStreamAsync().Result;
                    var fileLength = ms.Length;
                    var info = new FileInfo(item.Headers.ContentDisposition.FileName.Replace("\"", ""));
                    var allowFomat = new[] { ".png", ".jpg", ".jepg", ".gif" };
                    var isImage = allowFomat.Contains(info.Extension.ToLower());
                    var fileNewName = GetUniquelyString();
                    var localPath = HostingEnvironment.MapPath("~/upload/" + DateTime.Now.ToString("yyyyMMdd")) + "/" + fileNewName + info.Extension;
                    if (isImage)
                    {
                        if (!Directory.Exists(Path.GetDirectoryName(localPath)))
                        {
                            Directory.CreateDirectory(Path.GetDirectoryName(localPath));
                        }
                        byte[] fileBytes = new byte[fileLength];
                        ms.Read(fileBytes, 0, (int)fileLength);
//                        File.Create(localPath + "/" + fileNewName + info.Extension);
                        File.WriteAllBytes(localPath,fileBytes);
                        ms.Close();
                        fileNames.Add(DateTime.Now.ToString("yyyyMMdd") +"/" + fileNewName + info.Extension);                   
                    }

                }
            }
            return PageHelper.toJson(PageHelper.ReturnValue(true, string.Join("|", fileNames)));
        }
        public async Task<IHttpActionResult> Post()
        {
            try
            {
                if (!Request.Content.IsMimeMultipartContent())
                {
                    throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
                }

                var provider = new MultipartMemoryStreamProvider();
                await Request.Content.ReadAsMultipartAsync(provider);
                foreach (var file in provider.Contents.Where(x => x.Headers.ContentLength.HasValue && x.Headers.ContentLength.Value > 0))
                {
                    var fileName = file.Headers.ContentDisposition.FileName.Trim('\"');
                    var buffer = await file.ReadAsByteArrayAsync();

                    if(!Utilities.CanSaveFile(Utilities.DirectoryToSaveFiles, file.Headers.ContentLength.Value))
                    {
                        return InternalServerError();
                    }

                    File.WriteAllBytes(Path.Combine(Utilities.DirectoryToSaveFiles, fileName), buffer);
                }

                return Ok();
            }
            catch(Exception e)
            {
                return InternalServerError();
            }
        }
        public async Task<FilesUploadResponse> UploadFiles()
        {
            List<FileDescription> newFiles = new List<FileDescription>();

            if (!Request.Content.IsMimeMultipartContent())
                throw new Exception(); // divided by zero

            var provider = new MultipartMemoryStreamProvider();
            await Request.Content.ReadAsMultipartAsync(provider);
            foreach (var file in provider.Contents)
            {
                var filename = file.Headers.ContentDisposition.FileName.Trim('\"');
                var buffer = await file.ReadAsByteArrayAsync();
                //Do whatever you want with filename and its binaray data.

                var id = Guid.NewGuid();               
                newFiles.Add(new FileDescription()
                {
                    Id = id,
                    Name = filename,
                    Size = buffer.LongLength,
                    Url = "#"
                });
            }

            StaticFileStore.AddRange(newFiles);

            return new FilesUploadResponse { Files = newFiles };
        }
        public async Task<IHttpActionResult> Post()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                return BadRequest();
            }
            var provider = new MultipartMemoryStreamProvider();
            // путь к папке на сервере
            string root = System.Web.HttpContext.Current.Server.MapPath("~/UploadedFiles/");
            await Request.Content.ReadAsMultipartAsync(provider);

            foreach (var file in provider.Contents)
            {
                var filename = file.Headers.ContentDisposition.FileName.Trim('\"');
                byte[] fileArray = await file.ReadAsByteArrayAsync();

                using (System.IO.FileStream fs = new System.IO.FileStream(root + filename, System.IO.FileMode.Create))
                {
                    await fs.WriteAsync(fileArray, 0, fileArray.Length);
                }
                var temp = users.GetById(Convert.ToInt32(User.Identity.Name));
                temp.Photo = "UploadedFiles/" + filename;
                users.Edit(temp);
            }

            return Ok("OK");
        }
        public async Task<FormData> Convert(MultipartMemoryStreamProvider multipartProvider)
        {
            var multipartFormData = new FormData();

            foreach (var file in multipartProvider.Contents.Where(x => IsFile(x.Headers.ContentDisposition)))
            {
                var name = UnquoteToken(file.Headers.ContentDisposition.Name);
                string fileName = FixFilename(file.Headers.ContentDisposition.FileName);
                string mediaType = file.Headers.ContentType.MediaType;

                using (var stream = await file.ReadAsStreamAsync())
                {
                    byte[] buffer = ReadAllBytes(stream);
                    if (buffer.Length > 0)
                    {
                        multipartFormData.Add(name, new HttpFile(fileName, mediaType, buffer));
                    }
                }
            }

            foreach (var part in multipartProvider.Contents.Where(x => x.Headers.ContentDisposition.DispositionType == "form-data"
                                                                  && !IsFile(x.Headers.ContentDisposition)))
            {
                var name = UnquoteToken(part.Headers.ContentDisposition.Name);
                var data = await part.ReadAsStringAsync();
                multipartFormData.Add(name, data);
            }

            return multipartFormData;
        } 
Beispiel #13
0
        public async Task MultipleRangesGeneratesMultipartByteRangesContent(string ranges, int innerStreamLength, int expectedBodyparts, string[] contentRanges)
        {
            // Arrange
            string data = new String('a', innerStreamLength);

            byte[]           bytes     = Encoding.UTF8.GetBytes(data);
            MemoryStream     memStream = new MemoryStream(bytes);
            RangeHeaderValue range     = RangeHeaderValue.Parse(ranges);

            // Act
            ByteRangeStreamContent content = new ByteRangeStreamContent(memStream, range, _expectedMediatype);
            MemoryStream           result  = new MemoryStream();
            await content.CopyToAsync(result);

            MultipartMemoryStreamProvider multipart = await content.ReadAsMultipartAsync();

            // Assert
            Assert.Equal(expectedBodyparts, multipart.Contents.Count);
            for (int count = 0; count < multipart.Contents.Count; count++)
            {
                MediaTypeHeaderValue contentType = multipart.Contents[count].Headers.ContentType;
                Assert.Equal(_expectedMediatype, contentType);

                ContentRangeHeaderValue expectedContentRange = ContentRangeHeaderValue.Parse(contentRanges[count]);
                ContentRangeHeaderValue contentRange         = multipart.Contents[count].Headers.ContentRange;
                Assert.Equal(expectedContentRange, contentRange);
            }
        }
        // POST: /api/videos        
        public async Task<HttpResponseMessage> Post()
        {
            if (!Request.Content.IsMimeMultipartContent("form-data"))
            {
                throw new HttpResponseException(HttpStatusCode.NotAcceptable);
            }

            var streamProvider = new MultipartMemoryStreamProvider();
            var provider = await Request.Content.ReadAsMultipartAsync(streamProvider);

            var videoInf = VideoInformation.Parse(provider.Contents);
            var validationErrors = videoInf.GetErrors();
            var isValid = !validationErrors.Any();

            if (isValid)
            {
                var video =
                    await
                    this.service.CreateVideoAsync(
                        videoInf.Title,
                        videoInf.Description,
                        videoInf.FileInformation.Name,
                        videoInf.FileInformation.Type,
                        await videoInf.FileInformation.Data.ReadAsStreamAsync());

                return Request.CreateResponse(HttpStatusCode.Created, video);
            }
            else
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, string.Join("\n", validationErrors));
            }
        }
        public async Task<IHttpActionResult> Post()
        {
            try
            {
                if (!Request.Content.IsMimeMultipartContent())
                {
                    return BadRequest("Not Mime Multipart Content");
                }

                var provider = new MultipartMemoryStreamProvider();

                await Request.Content.ReadAsMultipartAsync(provider);

                var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Upload");

                foreach (var file in provider.Contents)
                {
                    var fileName = Path.GetFileName(file.Headers.ContentDisposition.FileName.Trim('\"'));
                    var fullPath = Path.Combine(path, fileName);
                    var buffer = await file.ReadAsByteArrayAsync();
                    File.WriteAllBytes(fullPath, buffer);
                }

                return Ok();
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
Beispiel #16
0
        public async Task<HttpResponseMessage> Post()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                return Request.CreateErrorResponse(HttpStatusCode.UnsupportedMediaType, "please submit a valid request");
            }
            var provider = new MultipartMemoryStreamProvider();
            try
            {
                await Request.Content.ReadAsMultipartAsync(provider);

                var file = provider.Contents.FirstOrDefault(x => !string.IsNullOrEmpty(x.Headers.ContentDisposition.FileName));
                if (file != null)
                {
                    InitHttpClient();
                    var stream = file.ReadAsStreamAsync().Result;
                    var filename = SaveFile(stream);
                    var products = _excelReader.GetProductsFromFile(filename);
                    var productsWithChangedProperties = FindProductsWithChangedProperties(products);

                    return Request.CreateResponse(HttpStatusCode.OK, productsWithChangedProperties, "application/json");
                }

                return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Неверный файл");
            }
            catch (System.Exception e)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
            }
        }
Beispiel #17
0
        public async Task<HttpResponseMessage> UploadFile()
        {
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);

            if (!Request.Content.IsMimeMultipartContent())
            {
                response.StatusCode = HttpStatusCode.UnsupportedMediaType;
            }
            else
            {
                UserPrincipal loggedInUser = (UserPrincipal)HttpContext.Current.User;
                MultipartMemoryStreamProvider provider = new MultipartMemoryStreamProvider();
                await Request.Content.ReadAsMultipartAsync(provider);
                Task<byte[]> fileData = provider.Contents.First().ReadAsByteArrayAsync();
                string fileName = string.Format("{0}.jpg", Guid.NewGuid().ToString());
                string directory = string.Format(@"{0}Uploads\{1}", AppDomain.CurrentDomain.BaseDirectory, loggedInUser.AccountSession.ClubId);

                if (!Directory.Exists(directory))
                    Directory.CreateDirectory(directory);

                using (FileStream fs = new FileStream(string.Format(@"{0}\{1}", directory, fileName), FileMode.OpenOrCreate))
                {
                    await fs.WriteAsync(fileData.Result, 0, fileData.Result.Length);
                    fs.Close();
                }

                response.Content = new ObjectContent<string>(fileName, new JsonMediaTypeFormatter());
            }

            return response;
        }
        // POST: api/SaveImages + ?id!
        //[Route("api/SaveImages/{id:int}")]
        public async Task<IHttpActionResult> PostSalonImage(int id, Boolean main, [FromUri]string username)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            // Check if the request contains multipart/form-data.
            if (Request.Content.IsMimeMultipartContent())
            {
                var streamProvider = new MultipartMemoryStreamProvider();
                streamProvider = await Request.Content.ReadAsMultipartAsync(streamProvider);

                foreach (var item in streamProvider.Contents.Where(c => !string.IsNullOrEmpty(c.Headers.ContentDisposition.FileName)))
                {
                    Stream stPictureSource = new MemoryStream(await item.ReadAsByteArrayAsync());

                    // Resize for Picture
                    MemoryStream stPictureDest = new MemoryStream();
                    var pictureSettings = new ResizeSettings
                    {
                        MaxWidth = 1000,
                        MaxHeight = 1000,
                        Mode = FitMode.Max
                    };
                    ImageBuilder.Current.Build(stPictureSource, stPictureDest, pictureSettings);

                    string fileName = item.Headers.ContentDisposition.FileName;

                    fileName = fileName.Replace("\"", string.Empty);

                    string ext = Path.GetExtension(fileName);

                    string newFileName = Guid.NewGuid().ToString() + ext;

                    File.WriteAllBytes(HostingEnvironment.MapPath("~/Images/SalonImages/" + newFileName), stPictureDest.ToArray());

                    db.SalonImages.Add(new SalonImage
                    {
                        AddedOn = DateTime.Now,
                        CreateBy = username,
                        ImageName = fileName,
                        ImagePath = newFileName,
                        IsDeleted = false,
                        IsMain = main,
                        SalonID = id,

                    });
                }

                await db.SaveChangesAsync();
                return Ok();
            }
            else
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

        }
        // POST api/values
        public async Task Post()
        {
            try
            {
                if (!Request.Content.IsMimeMultipartContent("form-data"))
                {
                    throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
                }

                var provider = new MultipartMemoryStreamProvider();

                // Read the form data.
                await Request.Content.ReadAsMultipartAsync(provider);

                var fileName = DateTime.Now.ToString("yyyyMMdd-HHmmss");
                var overlayText = string.Empty;
                var mediaType = string.Empty;
                var hubId = string.Empty;
                var username = string.Empty;

                byte[] bytes = null;
                foreach (var content in provider.Contents)
                {
                    if (content.Headers.ContentDisposition.Name.Trim('"').Equals("textOverlay", StringComparison.InvariantCultureIgnoreCase))
                    {
                        overlayText = await content.ReadAsStringAsync();
                    }
                    else if (content.Headers.ContentDisposition.Name.Trim('"').Equals("hubid", StringComparison.InvariantCultureIgnoreCase))
                    {
                        hubId = await content.ReadAsStringAsync();
                    }
                    else if (content.Headers.ContentDisposition.Name.Trim('"').Equals("username", StringComparison.InvariantCultureIgnoreCase))
                    {
                        username = await content.ReadAsStringAsync();
                    }
                    else if (content.Headers.ContentDisposition.Name.Trim('"').Equals("file", StringComparison.InvariantCultureIgnoreCase))
                    {
                        fileName += "-" + content.Headers.ContentDisposition.FileName.Trim('"');
                        mediaType = content.Headers.ContentType.MediaType;
                        bytes = await content.ReadAsByteArrayAsync();
                    }
                }

                await new GifStorageService().StoreGifAsync(
                    fileName,
                    bytes,
                    mediaType,
                    new Dictionary<string, string> 
                {
                    { "UserName", username },
                    { "OverlayText", overlayText },
                    { "HubId", hubId }
                });
            }
            catch (Exception)
            {
                throw;
            }
        }
Beispiel #20
0
        public void ReadAsMultipartAsync_SingleLongBodyPart(string boundary, string singleLongBody)
        {
            HttpContent content = CreateContent(boundary, singleLongBody);

            MultipartMemoryStreamProvider result = content.ReadAsMultipartAsync().Result;

            Assert.Equal(1, result.Contents.Count);
            Assert.Equal(singleLongBody, result.Contents[0].ReadAsStringAsync().Result);
            ValidateContents(result.Contents);
        }
Beispiel #21
0
        public async Task ReadAsMultipartAsync_SingleLongBodyPart(string boundary, string singleLongBody)
        {
            HttpContent content = CreateContent(boundary, singleLongBody);

            MultipartMemoryStreamProvider result = await content.ReadAsMultipartAsync();

            Assert.Equal(1, result.Contents.Count);
            Assert.Equal(singleLongBody, await result.Contents[0].ReadAsStringAsync());
            await ValidateContentsAsync(result.Contents);
        }
        public async System.Threading.Tasks.Task<HttpResponseMessage> UploadFile([FromBody]string id)
        {
            var supportedTypes = new List<string> { "png", "jpg", "jpeg", "gif" };
            if(!Request.Content.IsMimeMultipartContent())
            {
                return Request.CreateErrorResponse(HttpStatusCode.UnsupportedMediaType, "The request doesn't contain valid content!");
            }

            try
            {
                var provider = new MultipartMemoryStreamProvider();
                await Request.Content.ReadAsMultipartAsync(provider);

                string fileName = "";
                string fullpath = "";

                var file = provider.Contents.FirstOrDefault();
                if(file != null)
                {
                    if(string.IsNullOrEmpty(file.Headers.ContentDisposition.FileName))
                        throw new ArgumentNullException("file", "Invalid file provided!");

                    var serverPath = System.Web.HttpContext.Current.Server.MapPath("~/Images/Profile");
                    fileName = GetFileName(serverPath, file.Headers);
                    var ext = Path.GetExtension(fileName);

                    if(!supportedTypes.Contains(ext.Trim().TrimStart('.')))
                        throw new ArgumentException("Provided file type is not supported!");

                    fullpath = Path.Combine(serverPath, Path.GetFileName(fileName));

                    var dataStream = await file.ReadAsStreamAsync();

                    using(var fileStream = File.Create(fullpath))
                    {
                        dataStream.Seek(0, System.IO.SeekOrigin.Begin);
                        dataStream.CopyTo(fileStream);
                    }
                }

                var dbHelper = new MySqlPomocnik();

                //dbHelper.IzvrsiProceduru(new SqlUpit(), new Dictionary<string,object>());

                var response = Request.CreateResponse(HttpStatusCode.OK);

                response.Content = new StringContent(JSONHelper.ToJSON(new { fileName = fileName }), Encoding.UTF8, "text/plain");
                response.Content.Headers.ContentType = new MediaTypeWithQualityHeaderValue(@"text/html");
                return response;
            }
            catch(Exception e)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e.Message);
            }
        }
        public async Task ReadAsMultipartAsync_MultipleShortBodyParts(string boundary, string[] multipleShortBodies)
        {
            HttpContent content = CreateContent(boundary, multipleShortBodies);
            MultipartMemoryStreamProvider result = await content.ReadAsMultipartAsync();

            Assert.Equal(multipleShortBodies.Length, result.Contents.Count);
            for (var check = 0; check < multipleShortBodies.Length; check++)
            {
                Assert.Equal(multipleShortBodies[check], await result.Contents[check].ReadAsStringAsync());
            }

            await ValidateContentsAsync(result.Contents);
        }
Beispiel #24
0
        public void ReadAsMultipartAsync_MultipleLongBodyParts(string boundary, string[] multipleLongBodies)
        {
            HttpContent content = CreateContent(boundary, multipleLongBodies);
            MultipartMemoryStreamProvider result = content.ReadAsMultipartAsync(new MultipartMemoryStreamProvider(), ParserData.MinBufferSize).Result;

            Assert.Equal(multipleLongBodies.Length, result.Contents.Count);
            for (var check = 0; check < multipleLongBodies.Length; check++)
            {
                Assert.Equal(multipleLongBodies[check], result.Contents[check].ReadAsStringAsync().Result);
            }

            ValidateContents(result.Contents);
        }
Beispiel #25
0
        public void ReadAsMultipartAsync_WithHugeBody_AvoidStackOverflow()
        {
            // Arrange
            var         fiftyMegs = 1024 * 1024 * 50;
            HttpContent content   = CreateContent("---3123---", new string('x', fiftyMegs));

            // Act
            MultipartMemoryStreamProvider result = content.ReadAsMultipartAsync(new MultipartMemoryStreamProvider(), 256).Result;

            // Assert
            // this is for sanity. The actual test here is that the Act part did not cause a stack overflow
            Assert.Equal(fiftyMegs, result.Contents[0].ReadAsStringAsync().Result.Length);
            ValidateContents(result.Contents);
        }
Beispiel #26
0
        public async Task<IHttpActionResult> PostOpenFile()
        {
            var streamProvider = new MultipartMemoryStreamProvider();
            var multipartFileStreamProvider = await Request.Content.ReadAsMultipartAsync(streamProvider);

            if (multipartFileStreamProvider.Contents.Count == 0)
            {
                return BadRequest();
            }
            var fileName = streamProvider.Contents.First().Headers.ContentDisposition.FileName.Trim('"');
            var content = await streamProvider.Contents.First().ReadAsByteArrayAsync();
            var dataContainer = await _dataContainerConverterService.ToDataContainer(content, fileName);
            return Ok(dataContainer);
        }
Beispiel #27
0
        public void ReadAsMultipartAsync_MultipleShortBodyParts(string boundary)
        {
            string[] text = new string[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };

            HttpContent content = CreateContent(boundary, text);
            MultipartMemoryStreamProvider result = content.ReadAsMultipartAsync().Result;

            Assert.Equal(text.Length, result.Contents.Count);
            for (var check = 0; check < text.Length; check++)
            {
                Assert.Equal(text[check], result.Contents[check].ReadAsStringAsync().Result);
            }

            ValidateContents(result.Contents);
        }
        public void GetStreamReturnsMemoryStream()
        {
            MultipartMemoryStreamProvider instance = MultipartMemoryStreamProvider.Instance;
            HttpContent content = new StringContent("text");

            Stream stream = instance.GetStream(content.Headers);

            Assert.NotNull(stream);

            MemoryStream memStream = stream as MemoryStream;

            Assert.NotNull(stream);

            Assert.Equal(0, stream.Length);
            Assert.Equal(0, stream.Position);

            Assert.NotSame(memStream, instance.GetStream(content.Headers));
        }
        public async Task Put(int id, HttpRequestMessage request)
        {
            if (!Request.Content.IsMimeMultipartContent())
                throw new InvalidOperationException();

            var provider = new MultipartMemoryStreamProvider();
            await Request.Content.ReadAsMultipartAsync(provider);

            var file = provider.Contents.First();
            var filename = file.Headers.ContentDisposition.FileName.Trim('\"');
            var buffer = await file.ReadAsByteArrayAsync();
            var stream = new MemoryStream(buffer);

            using (var s = new StreamReader(stream))
            {
                var test = s;
            }
        }
		public async Task<HttpResponseMessage> ImportDatabase(int batchSize, bool includeExpiredDocuments, ItemType operateOnTypes, string filtersPipeDelimited, string transformScript)
		{
            if (!this.Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            var streamProvider = new MultipartMemoryStreamProvider();
            await Request.Content.ReadAsMultipartAsync(streamProvider);
            var fileStream = await streamProvider.Contents
                .First(c => c.Headers.ContentDisposition.Name == "\"file\"")
                .ReadAsStreamAsync();

            var dataDumper = new DataDumper(Database);
            var importOptions = new SmugglerImportOptions
            {
                FromStream = fileStream
            };
            var options = new SmugglerOptions
            {
                BatchSize = batchSize,
                ShouldExcludeExpired = includeExpiredDocuments,
                OperateOnTypes = operateOnTypes,
                TransformScript = transformScript
            };

            // Filters are passed in without the aid of the model binder. Instead, we pass in a list of FilterSettings using a string like this: pathHere;;;valueHere;;;true|||againPathHere;;;anotherValue;;;false
            // Why? Because I don't see a way to pass a list of a values to a WebAPI method that accepts a file upload, outside of passing in a simple string value and parsing it ourselves.
            if (filtersPipeDelimited != null)
            {
                options.Filters.AddRange(filtersPipeDelimited
                    .Split(new string[] { "|||" }, StringSplitOptions.RemoveEmptyEntries)
                    .Select(f => f.Split(new string[] { ";;;" }, StringSplitOptions.RemoveEmptyEntries))
                    .Select(o => new FilterSetting
                    {
                        Path = o[0],
                        Values = new List<string> { o[1] },
                        ShouldMatch = bool.Parse(o[2])
                    }));
            }

            await dataDumper.ImportData(importOptions, options);
            return GetEmptyMessage();
		}
        public async Task<HttpResponseMessage> Post()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            // Temp storage location for File Chunks
            MultipartMemoryStreamProvider provider = new MultipartMemoryStreamProvider();
            FileChunk chunk = null;

            try
            {
                // Read all contents of multipart message into MultipartMemoryStreamProvider.                 
                await Request.Content.ReadAsMultipartAsync(provider);

                using (Stream fileChunkStream = await provider.Contents[0].ReadAsStreamAsync())
                {

                    //Check for not null or empty
                    if (fileChunkStream == null)
                        throw new HttpResponseException(HttpStatusCode.NotFound);

                    // Read file chunk detail
                    chunk = provider.Contents[0].Headers.GetMetaData();
                    chunk.ChunkData = fileChunkStream.ReadFully();

                    // Upload Chunk to blob storage and store the reference in Azure Cache
                    _operations.UploadChunk(chunk);

                    // check for last chunk, if so, then do a PubBlockList
                    // Remove all keys of that FileID from Dictionary
                    if (chunk.IsCompleted)
                        _operations.CommitChunks(chunk);
                }

                // Send OK Response along with saved file names to the client.                 
                return Request.CreateResponse(HttpStatusCode.OK);
            }
            catch (System.Exception e)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
            }
        }
		public async Task<HttpResponseMessage> ImportDatabase()
		{
            if (!this.Request.Content.IsMimeMultipartContent()) 
            { 
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); 
            }

            var streamProvider = new MultipartMemoryStreamProvider();
            await Request.Content.ReadAsMultipartAsync(streamProvider);
            var fileStream = await streamProvider.Contents.First().ReadAsStreamAsync();
			var dataDumper = new DataDumper(Database);
            var importOptions = new SmugglerImportOptions
			{
                FromStream = fileStream
			};
            var options = new SmugglerOptions();
			await dataDumper.ImportData(importOptions, options);
            return GetEmptyMessage();
		}
Beispiel #33
0
        public void ReadAsMultipartAsync_MultipleLongBodyParts(string boundary)
        {
            string[] text = new string[] {
                "A" + LongText + "A",
                "B" + LongText + "B",
                "C" + LongText + "C",
                "D" + LongText + "D",
                "E" + LongText + "E",
                "F" + LongText + "F",
                "G" + LongText + "G",
                "H" + LongText + "H",
                "I" + LongText + "I",
                "J" + LongText + "J",
                "K" + LongText + "K",
                "L" + LongText + "L",
                "M" + LongText + "M",
                "N" + LongText + "N",
                "O" + LongText + "O",
                "P" + LongText + "P",
                "Q" + LongText + "Q",
                "R" + LongText + "R",
                "S" + LongText + "S",
                "T" + LongText + "T",
                "U" + LongText + "U",
                "V" + LongText + "V",
                "W" + LongText + "W",
                "X" + LongText + "X",
                "Y" + LongText + "Y",
                "Z" + LongText + "Z"
            };

            HttpContent content = CreateContent(boundary, text);
            MultipartMemoryStreamProvider result = content.ReadAsMultipartAsync(new MultipartMemoryStreamProvider(), ParserData.MinBufferSize).Result;

            Assert.Equal(text.Length, result.Contents.Count);
            for (var check = 0; check < text.Length; check++)
            {
                Assert.Equal(text[check], result.Contents[check].ReadAsStringAsync().Result);
            }

            ValidateContents(result.Contents);
        }
Beispiel #34
0
        public async Task<IHttpActionResult> MyFileUpload ()
        {
            var test = Request.GetQueryNameValuePairs();
            var id = test.First(f => f.Key == "id").Value.ToInt();

            if(!Request.Content.IsMimeMultipartContent())
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);

            var provider = new MultipartMemoryStreamProvider();
            await Request.Content.ReadAsMultipartAsync(provider);
            foreach(var file in provider.Contents)
            {
                var filename = file.Headers.ContentDisposition.FileName.Trim('\"');
                var buffer = await file.ReadAsByteArrayAsync();
                await usersBl.UpdateImage(id,filename,buffer);

            }

            return Ok(true);
        }
        // POST api/convertFiles?outputFormat=twl
        public async Task<IHttpActionResult> PostConvertFile(string outputFormat)
        {
            var streamProvider = new MultipartMemoryStreamProvider();
            var multipartFileStreamProvider = await Request.Content.ReadAsMultipartAsync(streamProvider);

            if (multipartFileStreamProvider.Contents.Count == 0)
            {
                return BadRequest();
            }
            var inputFormat = ConvertExtenstionToFormat(Path.GetExtension(streamProvider.Contents.First().Headers.ContentDisposition.FileName.Trim('\"')));
            var content = await streamProvider.Contents.First().ReadAsByteArrayAsync();
            if (outputFormat.Equals("geojson", StringComparison.InvariantCultureIgnoreCase))
            {
                var convertedGpx = await _gpsBabelGateway.ConvertFileFromat(content, inputFormat, ConvertExtenstionToFormat(".gpx"));
                var featureCollection = ConvertGpxContentToGeoJson(convertedGpx);
                return Ok(featureCollection);
            }
            var outputContent = await _gpsBabelGateway.ConvertFileFromat(content, inputFormat, outputFormat);
            return Ok(outputContent);
        }
Beispiel #36
0
        public async Task<IHttpActionResult> PostFormData()
        {
            var claimsIdentity = User.Identity as ClaimsIdentity;

            if (claimsIdentity == null)
                return InternalServerError();

            // Check if the request contains multipart/form-data.
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            var provider = new MultipartMemoryStreamProvider();
            await Request.Content.ReadAsMultipartAsync(provider);

            var url = await _uploadControllerService.UploadImage(provider.Contents);
            await _uploadControllerService.UpdateUserImage(claimsIdentity.GetUserId(), url);
            return Ok(url);
        }
Beispiel #37
0
        private async Task<RemoteFileFetcherGatewayResponse> GetFile(string url)
        {
            if (string.IsNullOrEmpty(url) == false)
            {
                var fetcher = _httpGatewayFactory.CreateRemoteFileFetcherGateway(_cache.Get(User.Identity.Name));
                return await fetcher.GetFileContent(url);
            }
            var streamProvider = new MultipartMemoryStreamProvider();
            var multipartFileStreamProvider = await Request.Content.ReadAsMultipartAsync(streamProvider);

            if (multipartFileStreamProvider.Contents.Count == 0)
            {
                return new RemoteFileFetcherGatewayResponse();
            }
            return new RemoteFileFetcherGatewayResponse
            {
                Content = await streamProvider.Contents.First().ReadAsByteArrayAsync(),
                FileName = streamProvider.Contents.First().Headers.ContentDisposition.FileName.Trim('"')
            };
        }
        public async Task<HttpResponseMessage> PostFile()
        {
            if (!Request.Content.IsMimeMultipartContent())
                throw new Exception();

            var provider = new MultipartMemoryStreamProvider();
            var result = new { files = new List<object>() };

            provider = await Request.Content.ReadAsMultipartAsync(provider);

            var file = provider.Contents.FirstOrDefault();
            if (file == null) return Request.CreateResponse(HttpStatusCode.BadRequest);
            var reading = await file.ReadAsByteArrayAsync();
            var stream = new MemoryStream(reading);
            var response = _validator.Validate(XElement.Load(stream));

            return !response.Successful
                ? Request.CreateResponse(HttpStatusCode.BadRequest, response.Errors)
                : Request.CreateResponse(HttpStatusCode.OK);
        }
        public async Task ReadAsAsync_WhenContentIsMultipartContentAndFormatterCanReadFromTheContent()
        {
            MultipartContent mimeContent = new MultipartContent();

            mimeContent.Add(new StringContent("multipartContent"));

            _formatterMock.Setup(f => f.CanWriteType(It.IsAny <Type>())).Returns(true);
            _formatterMock.Setup(f => f.CanReadType(It.IsAny <Type>())).Returns(true);
            _formatterMock.Setup(f => f.ReadFromStreamAsync(It.IsAny <Type>(), It.IsAny <Stream>(), It.IsAny <HttpContent>(), It.IsAny <IFormatterLogger>()))
            .Returns <Type, Stream, HttpContent, IFormatterLogger>(async(type, stream, content, logger) =>
            {
                MultipartMemoryStreamProvider provider = await content.ReadAsMultipartAsync();
                Assert.Equal(1, provider.Contents.Count);
                return(await provider.Contents[0].ReadAsStringAsync());
            });
            MediaTypeFormatter formatter = _formatterMock.Object;

            formatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("multipart/mixed"));

            Assert.Equal("multipartContent", await mimeContent.ReadAsAsync <string>(new[] { formatter }));
        }
        public async Task<IHttpActionResult> StoreImage()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            // TODO check size and type
            var provider = new MultipartMemoryStreamProvider();
            await Request.Content.ReadAsMultipartAsync(provider);
            var res = new List<ItemInfo>();
            foreach (var file in provider.Contents)
            {
                var filename = file.Headers.ContentDisposition.FileName.Trim('\"');
                var ext = Path.GetExtension(filename).TrimStart('.');
                var stream = await file.ReadAsStreamAsync();
                res.Add(this.mediaService.StoreImage(stream, ext));
            }

            return this.Ok(res);
        }
        public async Task<HttpResponseMessage> ImportExcelFile()
        {
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
            if (!Request.Content.IsMimeMultipartContent())
            {
                response.StatusCode = HttpStatusCode.UnsupportedMediaType;
            }
            else
            {
                MultipartMemoryStreamProvider provider = new MultipartMemoryStreamProvider();
                await Request.Content.ReadAsMultipartAsync(provider);
                Task<byte[]> fileData = provider.Contents.First().ReadAsByteArrayAsync();
                int formId = int.Parse(((System.Web.HttpContextWrapper)Request.Properties["MS_HttpContext"]).Request.Form["formId"]);

                FormExcelImportResult result = FormsBLL.SubmitExternalFormFromExcel(fileData.Result, formId);

                response.Content = new ObjectContent<FormExcelImportResult>(result, new JsonMediaTypeFormatter());
            }

            return response;
        }
Beispiel #42
0
        public async Task ReadAsMultipartAsync_NestedMultipartContent(string boundary)
        {
            const int    nesting   = 10;
            const string innerText = "Content";

            MultipartContent innerContent = new MultipartContent("mixed", boundary);

            innerContent.Add(new StringContent(innerText));
            for (var cnt = 0; cnt < nesting; cnt++)
            {
                string           outerBoundary = String.Format("{0}_{1}", boundary, cnt);
                MultipartContent outerContent  = new MultipartContent("mixed", outerBoundary);
                outerContent.Add(innerContent);
                innerContent = outerContent;
            }

            MemoryStream memStream = new MemoryStream();
            await innerContent.CopyToAsync(memStream);

            memStream.Position = 0;
            byte[]      data    = memStream.ToArray();
            HttpContent content = new ByteArrayContent(data);

            content.Headers.ContentType = innerContent.Headers.ContentType;

            for (var cnt = 0; cnt < nesting + 1; cnt++)
            {
                MultipartMemoryStreamProvider result = await content.ReadAsMultipartAsync();

                Assert.Equal(1, result.Contents.Count);
                content = result.Contents[0];
                Assert.NotNull(content);
            }

            string text = await content.ReadAsStringAsync();

            Assert.Equal(innerText, text);
        }
        public async Task ReadAsMultipartAsync_UsingMultipartContent(string boundary)
        {
            MultipartContent content = new MultipartContent("mixed", boundary);

            content.Add(new StringContent("A"));
            content.Add(new StringContent("B"));
            content.Add(new StringContent("C"));

            MemoryStream memStream = new MemoryStream();
            await content.CopyToAsync(memStream);

            memStream.Position = 0;
            byte[] data        = memStream.ToArray();
            var    byteContent = new ByteArrayContent(data);

            byteContent.Headers.ContentType = content.Headers.ContentType;

            MultipartMemoryStreamProvider result = await byteContent.ReadAsMultipartAsync();

            Assert.Equal(3, result.Contents.Count);
            Assert.Equal("A", await result.Contents[0].ReadAsStringAsync());
            Assert.Equal("B", await result.Contents[1].ReadAsStringAsync());
            Assert.Equal("C", await result.Contents[2].ReadAsStringAsync());
        }
        public void DefaultConstructor()
        {
            MultipartMemoryStreamProvider instance = MultipartMemoryStreamProvider.Instance;

            Assert.NotNull(instance);
        }
        public void GetStreamThrowsOnNull()
        {
            MultipartMemoryStreamProvider instance = MultipartMemoryStreamProvider.Instance;

            Assert.ThrowsArgumentNull(() => { instance.GetStream(null); }, "headers");
        }