private static string ParseImages(string body, MultipartFileStreamProvider multiPartRequest) { return(Regex.Replace(body, @"\[i:(\d+)\:(.*?)]", m => { var index = m.Groups[1].Value.TryConvertTo <int>(); if (index) { //get the file at this index var file = multiPartRequest.FileData[index.Result]; var rndId = Guid.NewGuid().ToString("N"); using (var stream = File.OpenRead(file.LocalFileName)) { var savedFile = UmbracoMediaFile.Save(stream, "articulate/" + rndId + "/" + file.Headers.ContentDisposition.FileName.TrimStart("\"").TrimEnd("\"")); var result = string.Format("![{0}]({1})", savedFile.Url, savedFile.Url ); return result; } } return m.Value; })); }
public async Task PostMultipartStream() { // Verify that this is an HTML Form file upload request if (!Request.Content.IsMimeMultipartContent("form-data")) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } string tempDir = HttpContext.Current.Server.MapPath("~/App_Data/temp"); var provider = new MultipartFileStreamProvider(tempDir); var multipart = await Request.Content.ReadAsMultipartAsync(provider); foreach (var fileData in multipart.FileData) { try { var lines = File.ReadAllLines(fileData.LocalFileName); var report = Parser.parse(lines); this.reportLoader.LoadReport(report); } finally { File.Delete(fileData.LocalFileName); } } }
public Task <HttpResponseMessage> UploadFile(HttpRequestMessage request, string path) { string rootPath = GetPath(path); var provider = new MultipartFileStreamProvider(rootPath); var newFullFilePath = ""; var task = request.Content.ReadAsMultipartAsync(provider).ContinueWith <HttpResponseMessage>(t => { List <string> savedFilePath = new List <string>(); if (t.IsCanceled || t.IsFaulted) { request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception); } foreach (MultipartFileData item in provider.FileData) { try { string name = item.Headers.ContentDisposition.FileName.Replace("\"", ""); // TODO: Don't allow executable extensions to be uploaded or use an ext whitelist? string newFileName = Guid.NewGuid() + Path.GetExtension(name); newFullFilePath = Path.Combine(rootPath, newFileName); File.Move(item.LocalFileName, newFullFilePath); } catch (Exception ex) { string message = ex.Message; } } FileInfo fi = new FileInfo(newFullFilePath); string relativePath = GetRelativeUploadPath(newFullFilePath); var downloadUrl = GetDownloadUrl(request.RequestUri, relativePath); var newFile = new[] { new SimpleFile { Name = fi.Name, Path = relativePath, IsDirectory = false, Extension = fi.Extension, LastModifiedTime = fi.LastWriteTimeUtc.ToString("MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture), Size = FileHelper.FormatByteSize(fi.Length, 0), DownloadUrl = downloadUrl } }; return(request.CreateResponse(HttpStatusCode.Created, newFile)); }); return(task); }
private static void CleanFiles(MultipartFileStreamProvider multiPartRequest) { foreach (var f in multiPartRequest.FileData) { File.Delete(f.LocalFileName); } }
public async Task <HttpResponseMessage> PostRawBufferManual() { MultipartFormDataStreamProvider streamProvider = new MultipartFormDataStreamProvider("~/App_Data"); MultipartFileStreamProvider dataContent = await Request.Content.ReadAsMultipartAsync(streamProvider); foreach (HttpContent data in dataContent.Contents) { string fileName = data.Headers.ContentDisposition.Name; byte[] n = await data.ReadAsByteArrayAsync(); string m = Encoding.ASCII.GetString(n); int z = int.Parse(m); imgEntity.UID = z; break; } foreach (HttpContent data in dataContent.Contents) { string fileNamePicture = data.Headers.ContentDisposition.Name; if (fileNamePicture == "picture") { byte[] b = await data.ReadAsByteArrayAsync(); imgEntity.Image = b; } } context.ImgEntitySet.Add(imgEntity); context.SaveChanges(); return(Request.CreateResponse(HttpStatusCode.OK)); }
public bool uploadpic(MultipartFileStreamProvider f, string id) { try { string filename = ""; string path = HttpContext.Current.Server.MapPath("~/Content/Temp/"); Random rand = new Random((int)DateTime.Now.Ticks); int numIterations = 0; foreach (MultipartFileData file in f.FileData) { numIterations = rand.Next(1, 99999); string ext = file.Headers.ContentDisposition.FileName.Split('.')[1]; filename = numIterations + "-" + id + "." + ext.Replace("\"", ""); string new_path = path + filename.Replace("\"", ""); File.Move(file.LocalFileName, new_path); try { AmazonS3Client S3Client = null; AmazonS3Config S3Config = new AmazonS3Config() { ServiceURL = "http://s3-external-1.amazonaws.com" }; string accessKey = WebConfigurationManager.AppSettings["AWSaccessKey"], secretAccessKey = WebConfigurationManager.AppSettings["AWSsecretAccessKey"], filePath = new_path, newFileName = filename; S3Client = new AmazonS3Client(accessKey, secretAccessKey, S3Config); var s3PutObject = new PutObjectRequest() { FilePath = filePath, BucketName = "hsrecs" + "/images", CannedACL = S3CannedACL.PublicRead }; if (!string.IsNullOrWhiteSpace(newFileName)) { s3PutObject.Key = newFileName; } s3PutObject.Headers.Expires = new DateTime(2020, 1, 1); PutObjectResponse s3PutResponse = S3Client.PutObject(s3PutObject); if (System.IO.File.Exists(filePath)) { System.IO.File.Delete(filePath); } } catch (Exception ex) { return(false); } } new_filename = filename; return(true); } catch (Exception ex) { return(false); } }
public async Task <HttpResponseMessage> PostFormData() { Console.WriteLine("UPLOAD"); var provider = new MultipartFileStreamProvider("C:\\test"); var task = Request.Content.ReadAsMultipartAsync(provider). ContinueWith(x => { var zipName = string.Format("db{0}.zip", counter); var file = string.Format("C:\\test\\{0}", zipName); counter++; if (File.Exists(file)) { File.Delete(file); } Console.WriteLine("Parts: {0}", provider.FileData.Count); foreach (var filePart in provider.FileData) { File.Copy(filePart.LocalFileName, file); File.Delete(filePart.LocalFileName); } var db = mongo.GetDatabase("sense"); using (ZipArchive archive = ZipFile.OpenRead(file)) { foreach (ZipArchiveEntry entry in archive.Entries) { string[] tokens = entry.Name.Split('_'); string deviceId = tokens[0]; string type = tokens[1]; var collection = db.GetCollection <BsonDocument>(type); using (Stream stream = entry.Open()) { var reader = new StreamReader(stream); while (!reader.EndOfStream) { collection.InsertOne(BsonDocument.Parse(reader.ReadLine())); } } } } File.Delete(file); return(Request.CreateResponse(System.Net.HttpStatusCode.OK)); }); var response = await task; return(response); }
public Task <HttpResponseMessage> Post() { List <string> savedFilePath = new List <string>(); Dictionary <string, string> attributes = new Dictionary <string, string>(); if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } //Where to put the picture on server ...MapPath("~/TargetDir") string rootPath = System.Web.HttpContext.Current.Server.MapPath("~/uploadFiles"); var provider = new MultipartFileStreamProvider(rootPath); string newFileName = string.Empty; Task <HttpResponseMessage> task = Request.Content.ReadAsMultipartAsync(provider). ContinueWith <HttpResponseMessage>(t => { if (t.IsCanceled || t.IsFaulted) { Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception); } foreach (MultipartFileData item in provider.FileData) { try { string name = item.Headers.ContentDisposition.FileName.Replace("\"", ""); newFileName = Path.GetFileNameWithoutExtension(name) + "_" + CreateDateTimeWithValidChars() + Path.GetExtension(name); string[] names = Directory.GetFiles(rootPath); foreach (var fileName in names) { if (Path.GetFileNameWithoutExtension(fileName).IndexOf(Path.GetFileNameWithoutExtension(name)) != -1) { File.Delete(fileName); } } File.Copy(item.LocalFileName, Path.Combine(rootPath, newFileName), true); File.Delete(item.LocalFileName); Uri baseuri = new Uri(Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.PathAndQuery, string.Empty)); string fileRelativePath = "~/uploadFiles/" + newFileName; Uri fileFullPath = new Uri(baseuri, VirtualPathUtility.ToAbsolute(fileRelativePath)); savedFilePath.Add(fileFullPath.ToString()); } catch (Exception ex) { Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message); } } //Save to DB Here . string filePath = Path.Combine(rootPath, newFileName); //MoveAndSaveFile(filePath); return(Request.CreateResponse(HttpStatusCode.Created, MoveAndSaveFile(filePath))); }); return(task); }
public async Task <FileUploadResponse.FileUpload> FileUpload() { bool operate = false; string fileName = null; DateTime date = DateTime.Now.AddYears(-21); //判断是否为正确的文件的格式multipart/form-data if (!Request.Content.IsMimeMultipartContent()) { return(new FileUploadResponse.FileUpload() { fileName = fileName, uploadTime = date.ToString(), operate = operate }); } //设置文件上传的文件夹目录 string rootPath = AppDomain.CurrentDomain.BaseDirectory + resourcePath; //创建multipart/form-data文件流提供者 var provider = new MultipartFileStreamProvider(rootPath); //等待异步读取multipart/form-data文件信息 await Request.Content.ReadAsMultipartAsync(provider); foreach (MultipartFileData item in provider.FileData) { try { //剪切的文件名 string name = item.Headers.ContentDisposition.FileName.Replace("\"", ""); var str = name.Split('.'); Console.WriteLine(str); if (str.Length >= 2) { date = DateTime.Now; fileName = date.ToFileTimeUtc() + "." + str[str.Length - 1]; //将文件转为(移动)正确的文件 File.Move(item.LocalFileName, Path.Combine(rootPath, fileName)); //File.Delete(item.LocalFileName); Console.WriteLine(Path.Combine(rootPath, fileName)); operate = true; } else { operate = false; } } catch (Exception ex) { string message = ex.Message; } } return(new FileUploadResponse.FileUpload() { fileName = fileName, uploadTime = date.ToString(), operate = operate }); }
public IHttpActionResult PostAddProduct([FromBody] ProductModel model) { List <string> savedFilePath = new List <string>(); // Check if the request contains multipart/form-data if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } //Get the path of folder where we want to upload all files. string rootPath = HttpContext.Current.Server.MapPath("~/Content/Images"); var provider = new MultipartFileStreamProvider(rootPath); // Read the form data. //If any error(Cancelled or any fault) occurred during file read , return internal server error var task = Request.Content.ReadAsMultipartAsync(provider). ContinueWith <HttpResponseMessage>(t => { if (t.IsCanceled || t.IsFaulted) { Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception); } foreach (MultipartFileData dataitem in provider.FileData) { try { //Replace / from file name string name = dataitem.Headers.ContentDisposition.FileName.Replace("\"", ""); //Create New file name using GUID to prevent duplicate file name string newFileName = Guid.NewGuid() + Path.GetExtension(name); //Move file from current location to target folder. File.Move(dataitem.LocalFileName, Path.Combine(rootPath, newFileName)); } catch (Exception ex) { string message = ex.Message; } } return(Request.CreateResponse(HttpStatusCode.Created, savedFilePath)); }); Product prdct = new Product(); prdct.Name = model.Name; prdct.price = model.price; prdct.Description = model.Description; //----------------------------------conversion-------------------------- db.Products.Add(prdct); db.SaveChanges(); return(Ok(new { Message = "error message" })); }
//Upload Profile Picture of User public Task <HttpResponseMessage> ProfilePictureUpload() { // Fetch User ID from Basic Authentication string ID = Thread.CurrentPrincipal.Identity.Name; // Create string type of list for save sile path List <string> saveFilePath = new List <string>(); //Check content is mime support ot not if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } //Find rootPath string rootPath = HttpContext.Current.Server.MapPath("~/App_Data"); //Create Provider object of MutipartFileStreamProvider var provider = new MultipartFileStreamProvider(rootPath); var task = Request.Content.ReadAsMultipartAsync(provider).ContinueWith <HttpResponseMessage>(t => { if (t.IsCanceled || t.IsFaulted) { Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception); } foreach (MultipartFileData item in provider.FileData) { try { string name = item.Headers.ContentDisposition.FileName.Replace("\"", ""); string newFileName = ID + Path.GetExtension(name); File.Move(item.LocalFileName, Path.Combine(rootPath, newFileName)); Uri baseuri = new Uri(Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.PathAndQuery, string.Empty)); string fileRelativePath = "~/App_Data/" + newFileName; Uri fileFullPath = new Uri(baseuri, VirtualPathUtility.ToAbsolute(fileRelativePath)); saveFilePath.Add(fileFullPath.ToString()); } catch (Exception) { throw; } } return(Request.CreateResponse(HttpStatusCode.Created, saveFilePath)); }); return(task); }
public Task <HttpResponseMessage> UploadFile() { List <string> savefilepath = new List <string>(); if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } string rootpath = HttpContext.Current.Server.MapPath("~/FilesUploaded"); var provider = new MultipartFileStreamProvider(rootpath); var task = Request.Content.ReadAsMultipartAsync(provider). ContinueWith <HttpResponseMessage>(t => { if (t.IsCanceled || t.IsFaulted) { Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception); } foreach (MultipartFileData item in provider.FileData) { try { string name = item.Headers.ContentDisposition.FileName.Replace("\"", ""); string newfilename = Guid.NewGuid() + Path.GetExtension(name); File.Move(item.LocalFileName, Path.Combine(rootpath, newfilename)); Uri baseuri = new Uri(Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.PathAndQuery, string.Empty)); string fileRelativePath = "~/FilesUploaded/" + newfilename; Uri filefullpath = new Uri(baseuri, VirtualPathUtility.ToAbsolute(fileRelativePath)); savefilepath.Add(filefullpath.ToString()); } catch (Exception) { throw; } } return(Request.CreateResponse(HttpStatusCode.Created, savefilepath)); }); return(task); }
public async Task <Dictionary <string, object> > UploadFile(int id) { Dictionary <string, object> results = new Dictionary <string, object>(); bool operate = false; //判断是否为正确的文件的格式multipart/form-data if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } //设置文件上传的文件夹目录 string rootPath = AppDomain.CurrentDomain.BaseDirectory + "upload"; //Console.WriteLine(AppDomain.CurrentDomain.BaseDirectory); //创建multipart/form-data文件流提供者 var provider = new MultipartFileStreamProvider(rootPath); //等待异步读取multipart/form-data文件信息 await Request.Content.ReadAsMultipartAsync(provider); foreach (MultipartFileData item in provider.FileData) { try { //剪切的文件名 string name = item.Headers.ContentDisposition.FileName.Replace("\"", ""); //Console.WriteLine(item.LocalFileName); //将文件转为(移动)正确的文件 File.Move(item.LocalFileName, Path.Combine(rootPath, name)); //File.Delete(item.LocalFileName); operate = true; //Console.WriteLine(Path.Combine(rootPath, name)); //Console.WriteLine(item.LocalFileName); //string name = item.Headers.ContentDisposition.FileName.Replace("\"", ""); //string newFileName = Guid.NewGuid().ToString("N") + Path.GetExtension(name); //File.Move(item.LocalFileName, Path.Combine(rootPath, newFileName)); //Request.RequestUri.PathAndQury为需要去掉域名的后面地址 //如上述请求为http://localhost:80824/api/upload/post,这就为api/upload/post //Request.RequestUri.AbsoluteUri则为http://localhost:8084/api/upload/post //Uri baseuri = new Uri(Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.PathAndQuery, string.Empty)); //string fileRelativePath = rootPath + "\\" + item.LocalFileName; //Uri fileFullPath = new Uri(baseuri, fileRelativePath); //savedFilePath.Add(fileFullPath.ToString()); } catch (Exception ex) { string message = ex.Message; } results.Add("operate", operate); } return(results); }
public async Task <IHttpActionResult> Upload(Guid profileId) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } try { var provider = new MultipartFileStreamProvider(Path.GetTempPath()); var content = new StreamContent(HttpContext.Current.Request.GetBufferlessInputStream(true)); foreach (var header in Request.Content.Headers) { content.Headers.TryAddWithoutValidation(header.Key, header.Value); } var tsk = await content.ReadAsMultipartAsync(provider); var result = new List <AudioFile>(); var docfiles = new List <string>(); foreach (var fileData in tsk.FileData) { AudioFile audioFile = null; // Sometimes the filename has a leading and trailing double-quote character // when uploaded, so we trim it; otherwise, we get an illegal character exception var fileName = Path.GetFileName(fileData.Headers.ContentDisposition.FileName.Trim('"')); var mediaType = fileData.Headers.ContentType.MediaType; var localFileName = fileData.LocalFileName; using (var fileStream = File.OpenRead(fileData.LocalFileName)) { fileStream.Position = 0; audioFile = new AudioFile(); audioFile.QrProfileId = profileId; audioFile.UploadedByUserId = this.User.Identity.GetUserId(); audioFile.UploadedOn = DateTime.Now; audioFile.Extension = Path.GetExtension(fileData.Headers.ContentDisposition.FileName.Replace("\"", "")); db.AudioFiles.Add(audioFile); var service = new BlobService(); await service.UploadBlob(audioFile.Id.ToString(), mediaType, fileStream, BlobHelper.Repository.Audio); await db.SaveChangesAsync(); } result.Add(audioFile); File.Delete(fileData.LocalFileName); } return(Ok(result)); } catch (InvalidDataException ex) { return(BadRequest(ex.Message)); } }
public async Task <IHttpActionResult> Post() { if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } var provider = new MultipartFileStreamProvider(HttpRuntime.AppDomainAppPath); await Request.Content.ReadAsMultipartAsync(provider); var filesInfo = provider.FileData.Select(file => SaveFile(file)); return(Content(HttpStatusCode.Created, filesInfo)); }
public async Task <HttpResponseMessage> Post(HttpRequestMessage message) { if (!Request.Content.IsMimeMultipartContent("form-data")) { return(message.CreateResponse(HttpStatusCode.UnsupportedMediaType)); } var streamProvider = new MultipartFileStreamProvider(Environment.CurrentDirectory); await Request.Content.ReadAsMultipartAsync(streamProvider); var fileNames = streamProvider.FileData.Select(f => f.Headers.ContentDisposition.Name); return(message.CreateResponse(HttpStatusCode.Created, fileNames.ToArray())); }
public static string GetTempFilepath(MultipartFileStreamProvider provider) { var appDataPath = AppUtil.GetAppDataPath(); var fileData = provider.FileData.First(); var localFileName = fileData.LocalFileName; var fileName = GetFileName(fileData); var outputPath = Path.Combine(appDataPath, $"{DateTime.Now:yyyyMMdd-HHmmss}-{fileName}"); File.Move(localFileName, outputPath); return(outputPath); }
public async Task <HttpResponseMessage> PostIt() { if (!Request.Content.IsMimeMultipartContent("form-data")) { //return ""; return(Request.CreateResponse(HttpStatusCode.InternalServerError)); } string folder = "C:\\Users\\Ben\\Temp"; MultipartFormDataStreamProvider p = new MultipartFormDataStreamProvider(folder); MultipartFileStreamProvider sp = await Request.Content.ReadAsMultipartAsync(p); return(Request.CreateResponse(HttpStatusCode.OK, "OK")); //return ""; }
public Task <HttpResponseMessage> Post() { List <string> savedFilePath = new List <string>(); // Check if the request contains multipart/form-data if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } //Get the path of folder where we want to upload all files. string rootPath = HttpContext.Current.Server.MapPath("~/App_Data"); var provider = new MultipartFileStreamProvider(rootPath); // Read the form data. //If any error(Cancelled or any fault) occurred during file read , return internal server error var task = Request.Content.ReadAsMultipartAsync(provider). ContinueWith <HttpResponseMessage>(t => { if (t.IsCanceled || t.IsFaulted) { Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception); } foreach (MultipartFileData dataitem in provider.FileData) { try { //Replace / from file name string name = dataitem.Headers.ContentDisposition.FileName.Replace("\"", ""); //Create New file name using GUID to prevent duplicate file name string newFileName = Guid.NewGuid() + Path.GetExtension(name); //Move file from current location to target folder. File.Move(dataitem.LocalFileName, Path.Combine(rootPath, newFileName)); return(Request.CreateResponse(HttpStatusCode.OK, rootPath + "\\" + newFileName)); } catch (Exception ex) { string message = ex.Message; } } return(Request.CreateResponse(HttpStatusCode.Created, savedFilePath)); }); return(task); }
public IHttpActionResult UploadFile() { //https://www.c-sharpcorner.com/article/how-to-dynamically-upload-and-play-video-file-using-asp-net-mvc-5/ //https://yogeshdotnet.com/web-api-2-file-upload-asp-net-mvc/ List <string> savedFilePath = new List <string>(); // Check if the request contains multipart/form-data if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } //Get the path of folder where we want to upload all files. string rootPath = HttpContext.Current.Server.MapPath("~/MediaContent"); var provider = new MultipartFileStreamProvider(rootPath); // Read the form data. //If any error(Cancelled or any fault) occurred during file read , return internal server error var task = Request.Content.ReadAsMultipartAsync(provider). ContinueWith <HttpResponseMessage>(t => { if (t.IsCanceled || t.IsFaulted) { Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception); } foreach (MultipartFileData dataitem in provider.FileData) { try { //Replace / from file name string name = dataitem.Headers.ContentDisposition.FileName.Replace("\"", ""); //Create New file name using GUID to prevent duplicate file name string newFileName = Guid.NewGuid() + Path.GetExtension(name); //Move file from current location to target folder. File.Move(dataitem.LocalFileName, Path.Combine(rootPath, newFileName)); } catch (Exception ex) { string message = ex.Message; } } return(Request.CreateResponse(HttpStatusCode.Created, savedFilePath)); }); return(Ok("UploadVideo")); }
// POST api/wavfiles public async Task <HttpResponseMessage> Post() { // Check if the request contains multipart/form-data. if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } string root = HttpContext.Current.Server.MapPath("~/Download_Data"); try { var provider = new MultipartFileStreamProvider(root); // Request.Content.ReadAsHttpRequestMessageAsync // Read the form data. await Request.Content.ReadAsMultipartAsync(provider); // This illustrates how to get the file names. foreach (MultipartFileData file in provider.FileData) { string fileName_Browser = file.Headers.ContentDisposition.FileName; fileName_Browser = fileName_Browser.Trim('"'); string[] parts = fileName_Browser.Split('_'); Trace.WriteLine("fileName for the Metadata File : " + root + "/" + parts[0] + "_" + parts[1] + "_" + parts[2] + ".txt"); using (StreamWriter sw = new StreamWriter(root + @"\" + parts[0] + "_" + parts[1] + "_" + parts[2] + ".txt", true)) { await sw.WriteLineAsync(parts[3] + ";" + file.LocalFileName + ";" + parts[4] + ";" + parts[5]); } Trace.WriteLine(file.Headers.ContentDisposition.FileName); Trace.WriteLine("Server file path: " + file.LocalFileName); } return(Request.CreateResponse(HttpStatusCode.OK)); } catch (Exception e) { return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e)); } }
private ParseImageResponse ParseImages(string body, MultipartFileStreamProvider multiPartRequest, bool extractFirstImageAsProperty) { var firstImage = string.Empty; var bodyText = Regex.Replace(body, @"\[i:(\d+)\:(.*?)]", m => { var index = m.Groups[1].Value.TryConvertTo <int>(); if (index) { //get the file at this index var file = multiPartRequest.FileData[index.Result]; var rndId = Guid.NewGuid().ToString("N"); using (var stream = File.OpenRead(file.LocalFileName)) { var fileUrl = "articulate/" + rndId + "/" + file.Headers.ContentDisposition.FileName.TrimStart("\"").TrimEnd("\""); _mediaFileSystem.AddFile(fileUrl, stream); var result = string.Format("![{0}]({1})", fileUrl, fileUrl ); if (extractFirstImageAsProperty && string.IsNullOrEmpty(firstImage)) { firstImage = fileUrl; //in this case, we've extracted the image, we don't want it to be displayed // in the content too so don't return it. return(string.Empty); } return(result); } } return(m.Value); }); return(new ParseImageResponse { BodyText = bodyText, FirstImage = firstImage }); }
private static IEnumerable <FormFile> ParsePostedFiles(MultipartFileStreamProvider multipartData) { var files = new List <FormFile>(); foreach (var file in multipartData.FileData) { var fi = new FileInfo(file.LocalFileName); files.Add(new FormFile { Key = file.Headers.ContentDisposition.Name.Replace("\"", String.Empty), ContentLength = (int)fi.Length, ContentType = file.Headers.ContentType.ToString(), FileName = file.Headers.ContentDisposition.FileName.Replace("\"", String.Empty), InputStream = File.OpenRead(fi.FullName) }); } return(files); }
public async Task <IHttpActionResult> AddProfilePicture(string userType, string userName) { var ctx = HttpContext.Current; var root = ctx.Server.MapPath("~/Content/ProfilePictures"); var provider = new MultipartFileStreamProvider(root); await Request.Content.ReadAsMultipartAsync(provider); foreach (var file in provider.FileData) { var name = file.Headers.ContentDisposition.FileName; name = name.Trim('"'); var localFileName = file.LocalFileName; name = DateTime.Now.ToString("yyyy-MM-dd") + "-" + DateTime.Now.ToString("hh-mm-ss") + name; var filePath = Path.Combine(root, name); var db = "Content/ProfilePictures/" + name; File.Move(localFileName, filePath); if (userType == "Customer") { var customer = customerrepo.GetByUserName(userName); customer.ProfilePicture = db; customerrepo.Update(customer); return(Created("http://localhost:51045/" + db, customer)); } else if (userType == "Vendor") { var vendor = vendorrepo.GetByUserName(userName); vendor.ProfilePicture = db; vendorrepo.Update(vendor); return(Created("http://localhost:51045/" + db, vendor)); } else { var employee = employeerepo.GetByUserName(userName); employee.ProfilePicture = db; employeerepo.Update(employee); return(Created("http://localhost:51045/" + db, employee)); } } return(StatusCode(HttpStatusCode.BadRequest)); }
async Task <File> handleFileUpload(int questionId) { var rootPath = ConfigurationManager.AppSettings["fileStorage"]; var tempath = rootPath + "\\temp"; if (!System.IO.Directory.Exists(tempath)) { System.IO.Directory.CreateDirectory(tempath); } var provider = new MultipartFileStreamProvider(tempath); if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotAcceptable, "Content MIME is not multipart")); } var result = await Request.Content.ReadAsMultipartAsync(provider); var tempFile = result.FileData.First(); var tempFilePath = tempFile.LocalFileName; var filename = this.generateRandomString(); var storagePath = rootPath + "\\storage\\"; var absolutePath = storagePath + filename; if (!System.IO.Directory.Exists(storagePath)) { System.IO.Directory.CreateDirectory(storagePath); } System.IO.File.Move(tempFilePath, absolutePath); return(new File { QuestionId = questionId, Path = filename, MediaType = tempFile.Headers.ContentType.MediaType, FileName = tempFile.Headers.ContentDisposition.FileName }); }
public async Task <HttpResponseMessage> PostSurveys() { var idService = HttpContext.Current.Request.Form["idService"]; BsonArray filesNames = MongoConnection.Instance.getServicio(Convert.ToInt32(idService)).fotos; string uploadFolder = HttpContext.Current.Server.MapPath("~/App_Data"); MultipartFormDataStreamProvider streamProvider = new MultipartFormDataStreamProvider(uploadFolder); MultipartFileStreamProvider multipartFileStreamProvider = await Request.Content.ReadAsMultipartAsync(streamProvider); string StoragePath = "~/Images/" + idService + "/"; String filePath = HostingEnvironment.MapPath(StoragePath); foreach (MultipartFileData fileData in streamProvider.FileData) { if (string.IsNullOrEmpty(fileData.Headers.ContentDisposition.FileName)) { return(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted")); } string fileName = fileData.Headers.ContentDisposition.FileName; if (fileName.StartsWith("\"") && fileName.EndsWith("\"")) { fileName = fileName.Trim('"'); } if (fileName.Contains(@"/") || fileName.Contains(@"\")) { fileName = Path.GetFileName(fileName); } if (fileName != "") { var tmp_name = Convert.ToString((DateTime.UtcNow.Subtract(new DateTime(2017, 1, 1))).TotalSeconds); tmp_name = tmp_name.Trim('.'); fileName = tmp_name + "_" + fileName; filesNames.Add(fileName); File.Move(fileData.LocalFileName, Path.Combine(filePath, fileName)); } } MongoConnection.Instance.addPhotos(filesNames, idService); return(Request.CreateResponse(HttpStatusCode.OK)); }
public async Task <IHttpActionResult> SaveImageItem(string storeId, string themeId, string folderName) { if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } var provider = new MultipartFileStreamProvider(_pathForMultipart); await Request.Content.ReadAsMultipartAsync(provider); var loadItemInfo = new LoadItemInfo(); foreach (var file in provider.FileData) { var fileInfo = new FileInfo(file.LocalFileName); using (FileStream stream = fileInfo.OpenRead()) { var fileName = file.Headers.ContentDisposition.FileName.Replace("\"", string.Empty); var filePath = string.Format("{0}{1}", _pathForFiles, fileName); using (var f = File.Create(filePath)) { await stream.CopyToAsync(f); } loadItemInfo.Name = fileName; loadItemInfo.ContentType = file.Headers.ContentType.MediaType; if (ContentTypeUtility.IsImageContentType(loadItemInfo.ContentType)) { loadItemInfo.Content = ContentTypeUtility. ConvertImageToBase64String(File.ReadAllBytes(filePath), file.Headers.ContentType.MediaType); } } } return(this.Ok(loadItemInfo)); }
public async Task <IHttpActionResult> AddPicture([FromUri] int id) { var ctx = HttpContext.Current; var root = ctx.Server.MapPath("~/Content/ProfilePictures"); var provider = new MultipartFileStreamProvider(root); await Request.Content.ReadAsMultipartAsync(provider); foreach (var file in provider.FileData) { var name = file.Headers.ContentDisposition.FileName; name = name.Trim('"'); var localFileName = file.LocalFileName; name = DateTime.Now.ToString("yyyy-MM-dd") + "-" + DateTime.Now.ToString("hh-mm-ss") + name; var filePath = Path.Combine(root, name); var db = "Content/ProfilePictures/" + name; File.Move(localFileName, filePath); var registartion = rrrepo.GetById(id); registartion.ProfilePicture = db; rrrepo.Update(registartion); return(Created("http://localhost:51045/" + db, registartion)); } return(StatusCode(HttpStatusCode.BadRequest)); }
public async Task <HttpResponseMessage> ImportDatabase(int batchSize, bool includeExpiredDocuments, bool stripReplicationInformation, ItemType operateOnTypes, string filtersPipeDelimited, string transformScript) { if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } string tempPath = Path.GetTempPath(); var fullTempPath = tempPath + Constants.TempUploadsDirectoryName; if (File.Exists(fullTempPath)) { File.Delete(fullTempPath); } if (Directory.Exists(fullTempPath) == false) { Directory.CreateDirectory(fullTempPath); } var streamProvider = new MultipartFileStreamProvider(fullTempPath); await Request.Content.ReadAsMultipartAsync(streamProvider).ConfigureAwait(false); var uploadedFilePath = streamProvider.FileData[0].LocalFileName; string fileName = null; var fileContent = streamProvider.Contents.SingleOrDefault(); if (fileContent != null) { fileName = fileContent.Headers.ContentDisposition.FileName.Replace("\"", string.Empty); } var status = new ImportOperationStatus(); var cts = new CancellationTokenSource(); var task = Task.Run(async() => { try { using (var fileStream = File.Open(uploadedFilePath, FileMode.Open, FileAccess.Read)) { var dataDumper = new DatabaseDataDumper(Database); dataDumper.Progress += s => status.LastProgress = s; var smugglerOptions = dataDumper.Options; smugglerOptions.BatchSize = batchSize; smugglerOptions.ShouldExcludeExpired = !includeExpiredDocuments; smugglerOptions.StripReplicationInformation = stripReplicationInformation; smugglerOptions.OperateOnTypes = operateOnTypes; smugglerOptions.TransformScript = transformScript; smugglerOptions.CancelToken = cts; // 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) { smugglerOptions.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(new SmugglerImportOptions <RavenConnectionStringOptions> { FromStream = fileStream }); } } catch (Exception e) { status.Faulted = true; status.State = RavenJObject.FromObject(new { Error = e.ToString() }); if (cts.Token.IsCancellationRequested) { status.State = RavenJObject.FromObject(new { Error = "Task was cancelled" }); cts.Token.ThrowIfCancellationRequested(); //needed for displaying the task status as canceled and not faulted } if (e is InvalidDataException) { status.ExceptionDetails = e.Message; } else if (e is Imports.Newtonsoft.Json.JsonReaderException) { status.ExceptionDetails = "Failed to load JSON Data. Please make sure you are importing .ravendump file, exported by smuggler (aka database export). If you are importing a .ravnedump file then the file may be corrupted"; } else { status.ExceptionDetails = e.ToString(); } throw; } finally { status.Completed = true; File.Delete(uploadedFilePath); } }, cts.Token); long id; Database.Tasks.AddTask(task, status, new TaskActions.PendingTaskDescription { StartTime = SystemTime.UtcNow, TaskType = TaskActions.PendingTaskType.ImportDatabase, Payload = fileName, }, out id, cts); return(GetMessageWithObject(new { OperationId = id })); }
public Task <HttpResponseMessage> Post() { string outputForNir = "start---"; List <string> savedFilePath = new List <string>(); if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } //Where to put the picture on server ...MapPath("~/TargetDir") //string rootPath = HttpContext.Current.Server.MapPath("~/uploadFiles"); string rootPath = HttpContext.Current.Server.MapPath("~/Userimage"); var provider = new MultipartFileStreamProvider(rootPath); var task = Request.Content.ReadAsMultipartAsync(provider). ContinueWith <HttpResponseMessage>(t => { if (t.IsCanceled || t.IsFaulted) { Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception); } foreach (MultipartFileData item in provider.FileData) { try { outputForNir += " ---here"; string name = item.Headers.ContentDisposition.FileName.Replace("\"", ""); outputForNir += " ---here2=" + name; //need the guid because in react native in order to refresh an inamge it has to have a new name string newFileName = Path.GetFileNameWithoutExtension(name) + "_" + CreateDateTimeWithValidChars() + Path.GetExtension(name); //string newFileName = Path.GetFileNameWithoutExtension(name) + "_" + Guid.NewGuid() + Path.GetExtension(name); //string newFileName = name + "" + Guid.NewGuid(); outputForNir += " ---here3" + newFileName; //delete all files begining with the same name string[] names = Directory.GetFiles(rootPath); foreach (var fileName in names) { if (Path.GetFileNameWithoutExtension(fileName).IndexOf(Path.GetFileNameWithoutExtension(name)) != -1) { File.Delete(fileName); } } //File.Move(item.LocalFileName, Path.Combine(rootPath, newFileName)); File.Copy(item.LocalFileName, Path.Combine(rootPath, newFileName), true); File.Delete(item.LocalFileName); outputForNir += " ---here4"; Uri baseuri = new Uri(Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.PathAndQuery, string.Empty)); outputForNir += " ---here5"; // string fileRelativePath = "~/uploadFiles/" + newFileName; string fileRelativePath = "~/Userimage/" + newFileName; outputForNir += " ---here6 imageName=" + fileRelativePath; Uri fileFullPath = new Uri(baseuri, VirtualPathUtility.ToAbsolute(fileRelativePath)); outputForNir += " ---here7" + fileFullPath.ToString(); savedFilePath.Add(fileFullPath.ToString()); } catch (Exception ex) { outputForNir += " ---excption=" + ex.Message; string message = ex.Message; } } return(Request.CreateResponse(HttpStatusCode.Created, "nirchen " + savedFilePath[0] + "!" + provider.FileData.Count + "!" + outputForNir + ":)")); }); return(task); }