/// <summary> /// Retrieves and parses the content disposition header from a section /// </summary> /// <param name="section">The section from which to retrieve</param> /// <returns>A <see cref="ContentDispositionHeaderValue"/> if the header was found, null otherwise</returns> public static ContentDispositionHeaderValue GetContentDispositionHeader(this MultipartSection section) => !ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var header) ? null : header;
public async Task <IActionResult> Upload([FromForm] PictureFormData pictureFormData) { var filePath = Path.GetTempFileName(); if (pictureFormData.File == null) { return(NotFound("Veuillez envoyer un fichier.")); } if (pictureFormData.File.Length > 0) { using (var stream = new FileStream(filePath, FileMode.Create)) { await pictureFormData.File.CopyToAsync(stream); using (var memoryStream = new MemoryStream()) { await pictureFormData.File.CopyToAsync(memoryStream); if (memoryStream.Length < 4194304) { stream.CopyTo(memoryStream); var mbytes = memoryStream.ToArray(); if (mbytes == null) { return(BadRequest("Error with file!")); } ProfilePicture newPic = _profilePictureService.Create(new ProfilePicture( pictureFormData.UserId, ContentDispositionHeaderValue.Parse(pictureFormData.File.ContentDisposition).FileName.Trim('"'), pictureFormData.File.ContentType, mbytes )); if (newPic == null) { return(BadRequest("Error while saving profile picture, empty file.")); } return(Ok(newPic)); } else { return(BadRequest("File size must not exceed 4MB.")); } } } } return(BadRequest("Error creating picture")); }
private async Task <IFormCollection> InnerReadFormAsync(CancellationToken cancellationToken) { if (!HasFormContentType) { throw new InvalidOperationException("Incorrect Content-Type: " + _request.ContentType); } cancellationToken.ThrowIfCancellationRequested(); if (_request.ContentLength == 0) { return(FormCollection.Empty); } if (_options.BufferBody) { _request.EnableRewind(_options.MemoryBufferThreshold, _options.BufferBodyLengthLimit); } FormCollection formFields = null; FormFileCollection files = null; // Some of these code paths use StreamReader which does not support cancellation tokens. using (cancellationToken.Register((state) => ((HttpContext)state).Abort(), _request.HttpContext)) { var contentType = ContentType; // Check the content-type if (HasApplicationFormContentType(contentType)) { var encoding = FilterEncoding(contentType.Encoding); using (var formReader = new FormReader(_request.Body, encoding) { ValueCountLimit = _options.ValueCountLimit, KeyLengthLimit = _options.KeyLengthLimit, ValueLengthLimit = _options.ValueLengthLimit, }) { formFields = new FormCollection(await formReader.ReadFormAsync(cancellationToken)); } } else if (HasMultipartFormContentType(contentType)) { var formAccumulator = new KeyValueAccumulator(); var boundary = GetBoundary(contentType, _options.MultipartBoundaryLengthLimit); var multipartReader = new MultipartReader(boundary, _request.Body) { HeadersCountLimit = _options.MultipartHeadersCountLimit, HeadersLengthLimit = _options.MultipartHeadersLengthLimit, BodyLengthLimit = _options.MultipartBodyLengthLimit, }; var section = await multipartReader.ReadNextSectionAsync(cancellationToken); while (section != null) { // Parse the content disposition here and pass it further to avoid reparsings if (!ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var contentDisposition)) { throw new InvalidDataException("Form section has invalid Content-Disposition value: " + section.ContentDisposition); } if (contentDisposition.IsFileDisposition()) { var fileSection = new FileMultipartSection(section, contentDisposition); // Enable buffering for the file if not already done for the full body section.EnableRewind( _request.HttpContext.Response.RegisterForDispose, _options.MemoryBufferThreshold, _options.MultipartBodyLengthLimit); // Find the end await section.Body.DrainAsync(cancellationToken); var name = fileSection.Name; var fileName = fileSection.FileName; FormFile file; if (section.BaseStreamOffset.HasValue) { // Relative reference to buffered request body file = new FormFile(_request.Body, section.BaseStreamOffset.GetValueOrDefault(), section.Body.Length, name, fileName); } else { // Individually buffered file body file = new FormFile(section.Body, 0, section.Body.Length, name, fileName); } file.Headers = new HeaderDictionary(section.Headers); if (files == null) { files = new FormFileCollection(); } if (files.Count >= _options.ValueCountLimit) { throw new InvalidDataException($"Form value count limit {_options.ValueCountLimit} exceeded."); } files.Add(file); } else if (contentDisposition.IsFormDisposition()) { var formDataSection = new FormMultipartSection(section, contentDisposition); // Content-Disposition: form-data; name="key" // // value // Do not limit the key name length here because the multipart headers length limit is already in effect. var key = formDataSection.Name; var value = await formDataSection.GetValueAsync(); formAccumulator.Append(key, value); if (formAccumulator.ValueCount > _options.ValueCountLimit) { throw new InvalidDataException($"Form value count limit {_options.ValueCountLimit} exceeded."); } } else { System.Diagnostics.Debug.Assert(false, "Unrecognized content-disposition for this section: " + section.ContentDisposition); } section = await multipartReader.ReadNextSectionAsync(cancellationToken); } if (formAccumulator.HasValues) { formFields = new FormCollection(formAccumulator.GetResults(), files); } } } // Rewind so later readers don't have to. if (_request.Body.CanSeek) { _request.Body.Seek(0, SeekOrigin.Begin); } if (formFields != null) { Form = formFields; } else if (files != null) { Form = new FormCollection(null, files); } else { Form = FormCollection.Empty; } return(Form); }
public async Task <User> Add(PaymentNotification paymentNotification, IFormFile[] images) { var user = await _context.Users.Where(x => x.Email == paymentNotification.Email).FirstOrDefaultAsync(); if (user == null) { throw new AppException("User is not found"); } if (images != null) { for (int i = 0; i < images.Length; i++) { if (images[i] != null && images[i].Length > 0) { var file = images[i]; if (file.Length > 0) { if (!file.ContentType.StartsWith("image")) { var fileLength = file.Length / 1024; var maxFileLength = 5120; if (fileLength > maxFileLength) { throw new AppException("Uploaded file must not be more than 5MB!"); } } } } } } if (images != null) { for (int i = 0; i < images.Length; i++) { Bitmap originalFile = null; Bitmap resizedFile = null; int imgWidth = 0; int imgHeigth = 0; if ((i == 0) && (images[i] != null) && (images[i].Length > 0)) { var uploads = Path.GetFullPath(Path.Combine(GlobalVariables.ImagePath, @"images\payment")); var file = images[i]; if (file.Length > 0) { var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim(); string uniqueFileName = paymentNotification.FirstName.Substring(0, 5) + i + DateTime.Now + file.FileName; string uniqueFileNameTrimmed = uniqueFileName.Replace(":", "").Replace("-", "").Replace(" ", "").Replace("/", ""); using (var fileStream = new FileStream(Path.Combine(uploads, uniqueFileNameTrimmed), FileMode.Create)) { await file.CopyToAsync(fileStream); paymentNotification.ImageNames = uniqueFileNameTrimmed; if (file.ContentType.StartsWith("image")) { int width = 200; int height = 200; originalFile = new Bitmap(fileStream); resizedFile = ResizeImage.GetResizedImage(fileStream, width, height, width, height); } } if (resizedFile != null) { imgWidth = resizedFile.Width; imgHeigth = resizedFile.Height; using (var fileStreamUp = new FileStream(Path.Combine(uploads, uniqueFileNameTrimmed), FileMode.Create)) { resizedFile.Save(fileStreamUp, ImageFormat.Jpeg); } } } } } } DateTime paymentNotificationLocalDate_Nigeria = new DateTime(); string windowsTimeZone = GetWindowsFromOlson.GetWindowsFromOlsonFunc("Africa/Lagos"); paymentNotificationLocalDate_Nigeria = TimeZoneInfo.ConvertTime(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById(windowsTimeZone)); paymentNotification.DateAdded = paymentNotificationLocalDate_Nigeria; int length = GlobalVariables.RandomStringLengthShort(); var randomKey = ""; var keyIsAlreadyPresent = true; do { randomKey = GlobalVariables.RandomString(length); keyIsAlreadyPresent = _context.PaymentNotifications.Any(x => x.Reference == randomKey); } while (keyIsAlreadyPresent); paymentNotification.Reference = randomKey; paymentNotification.Confirmed = "No"; paymentNotification.UpdateAllowed = true; await _context.PaymentNotifications.AddAsync(paymentNotification); if (paymentNotification.TransactionType == "Activation") { user.ActivationRequested = true; _context.Users.Update(user); } await _context.SaveChangesAsync(); //ThreadPool.QueueUserWorkItem(o => { string body = "Dear " + paymentNotification.FirstName + ",<br/><br/>Thank you for submitting your payment notification.<br/><br/>" + "We will confirm your payment and update your online profile.<br/><br/>" + "You will also receive an email from us as soon as we have confirmed your payment<br/><br/>" + "Thanks,<br/>The RotatePay Team<br/>"; var message = new Message(new string[] { paymentNotification.Email }, "[RotatePay] Payment Notification Received", body, null); _emailSenderService.SendEmail(message); string body1 = paymentNotification.FirstName + "(" + paymentNotification.Email + ") has submitted the payment notification form.<br/><br/><br/>"; var message1 = new Message(new string[] { GlobalVariables.AdminEmail }, "[RotatePay] Payment receipt by " + paymentNotification.Email, body1, images); _emailSenderService.SendEmail(message1); //}); //await _logService.Create(log); return(user); }
public static string GetFilename(this IFormFile file) { return(ContentDispositionHeaderValue.Parse( file.ContentDisposition).FileName.ToString().Trim('"')); }
public async Task <IActionResult> ImportBulkCopy(IList <IFormFile> files) { if (files != null && files.Count > 0) { try { var file = files[0]; var filename = ContentDispositionHeaderValue .Parse(file.ContentDisposition) .FileName .Trim('"'); string folder = _hostingEnvironment.WebRootPath + $@"\uploaded\excels"; if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } string filePath = Path.Combine(folder, filename); using (FileStream fs = System.IO.File.Create(filePath)) { file.CopyTo(fs); fs.Flush(); } //Import ExcelPackage.LicenseContext = LicenseContext.NonCommercial; using (var package = new ExcelPackage(new FileInfo(filePath))) { ExcelWorksheet workSheet = package.Workbook.Worksheets[0]; await _hubContext.Clients.All.SendAsync("StartBulkCopy"); bool hasHeader = true; DataTable tbl = new DataTable(); foreach (var firstRowCell in workSheet.Cells[1, 1, 1, workSheet.Dimension.End.Column]) { tbl.Columns.Add(hasHeader ? firstRowCell.Text : string.Format("Column {0}", firstRowCell.Start.Column)); } var startRow = hasHeader ? 2 : 1; for (int rowNum = startRow; rowNum <= workSheet.Dimension.End.Row; rowNum++) { var wsRow = workSheet.Cells[rowNum, 1, rowNum, workSheet.Dimension.End.Column]; DataRow row = tbl.Rows.Add(); foreach (var cell in wsRow) { row[cell.Start.Column - 1] = cell.Text; } } await _hubContext.Clients.All.SendAsync("CompleteConvertToDataTable"); string conStr = _constants.ConnectionStr; using (SqlConnection sqlConn = new SqlConnection(conStr)) { sqlConn.Open(); using (SqlBulkCopy sqlbc = new SqlBulkCopy(sqlConn)) { //donation sqlbc.DestinationTableName = "donation_1"; sqlbc.ColumnMappings.Add("id", "id"); sqlbc.ColumnMappings.Add("parent_id", "parent_id"); sqlbc.ColumnMappings.Add("elec_code", "elec_code"); sqlbc.ColumnMappings.Add("senator_id", "senator_id"); sqlbc.ColumnMappings.Add("amount", "amount"); sqlbc.ColumnMappings.Add("representative_name", "representative_name"); sqlbc.ColumnMappings.Add("postal_code", "postal_code"); sqlbc.ColumnMappings.Add("address", "address"); sqlbc.ColumnMappings.Add("occupation_id", "occupation_id"); sqlbc.ColumnMappings.Add("receipt_no", "receipt_no"); //history //sqlbc.DestinationTableName = "history"; //sqlbc.ColumnMappings.Add("id", "id"); //sqlbc.ColumnMappings.Add("donation_id", "donation_id"); //sqlbc.ColumnMappings.Add("modified_datetime", "modified_datetime"); //sqlbc.ColumnMappings.Add("modified_person", "modified_person"); //sqlbc.ColumnMappings.Add("change_process", "change_process"); //sqlbc.ColumnMappings.Add("content_change", "content_change"); //sqlbc.ColumnMappings.Add("send_from_process", "send_from_process"); //sqlbc.BulkCopyTimeout = 0; //sqlbc.BatchSize = 100; sqlbc.WriteToServer(tbl); await _hubContext.Clients.All.SendAsync("CompleteWriteToServer"); _repository.MergeTable(); await _hubContext.Clients.All.SendAsync("CompleteImport"); } } return(new NoContentResult()); } } catch (Exception ex) { throw ex; return(new BadRequestResult()); } } return(new BadRequestResult()); }
// 如果一个section的Header是: Content-Disposition: form-data; name="myfile1"; filename="Misc 002.jpg" // 那么本方法返回: Misc 002.jpg public static string GetFileName(ContentDispositionHeaderValue contentDisposition) { return(contentDisposition.FileName.Value); }
public async Task <IActionResult> CreateAndUploadData(int instanceOwnerId, Guid instanceId, string formId) { if (instanceOwnerId == 0 || instanceId == null || string.IsNullOrEmpty(formId) || Request.Body == null) { return(BadRequest("Missing parameter values: instanceOwnerId, instanceId, formId or file content cannot be null")); } // check if instance id exist and user is allowed to change the instance data Instance instance = await _instanceRepository.GetOneAsync(instanceId, instanceOwnerId); if (instance == null) { return(NotFound("Provided instanceId is unknown to platform storage service")); } // check if data element exists, if so raise exception if (instance.Data != null && instance.Data.ContainsKey(formId)) { return(Forbid("Data element allready exists, try Put instead of Post")); } // check metadata ApplicationInformation appInfo = GetApplicationInformation(instance.ApplicationId); if (appInfo == null || !appInfo.Forms.ContainsKey(formId)) { return(Forbid("Application information has not registered a form with this formId")); } FormDefinition form = appInfo.Forms[formId]; DateTime creationTime = DateTime.UtcNow; Stream theStream = null; string contentType = null; string contentFileName = null; if (MultipartRequestHelper.IsMultipartContentType(Request.ContentType)) { // Only read the first section of the mulitpart message. MediaTypeHeaderValue mediaType = MediaTypeHeaderValue.Parse(Request.ContentType); string boundary = MultipartRequestHelper.GetBoundary(mediaType, _defaultFormOptions.MultipartBoundaryLengthLimit); MultipartReader reader = new MultipartReader(boundary, Request.Body); MultipartSection section = await reader.ReadNextSectionAsync(); theStream = section.Body; contentType = section.ContentType; ContentDispositionHeaderValue contentDisposition; bool hasContentDisposition = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out contentDisposition); if (hasContentDisposition) { contentFileName = contentDisposition.FileName.ToString(); } } else { theStream = Request.Body; contentType = Request.ContentType; } if (theStream == null) { return(BadRequest("No data attachements found")); } // create new data element, store data in blob Data newData = new Data { // update data record Id = Guid.NewGuid().ToString(), ContentType = contentType, CreatedBy = User.Identity.Name, CreatedDateTime = creationTime, FileName = contentFileName, LastChangedBy = User.Identity.Name, LastChangedDateTime = creationTime, }; string fileName = GetFileName(instanceId, formId, instance, newData); newData.StorageUrl = fileName; if (instance.Data == null) { instance.Data = new Dictionary <string, Dictionary <string, Data> >(); } if (!instance.Data.ContainsKey(formId)) { instance.Data[formId] = new Dictionary <string, Data>(); } instance.Data[formId][newData.Id] = newData; // store file as blob await _dataRepository.CreateDataInStorage(theStream, fileName); // update instance Instance result = await _instanceRepository.UpdateInstanceInCollectionAsync(instanceId, instance); return(Ok(result)); }
public async Task <IActionResult> OverwriteData(int instanceOwnerId, Guid instanceId, string formId, Guid dataId) { if (instanceOwnerId == 0 || dataId == null || instanceId == null || string.IsNullOrEmpty(formId) || Request.Body == null) { return(BadRequest("Missing parameter values: instanceOwnerId, instanceId, formId or file content cannot be null")); } // check if instance id exist and user is allowed to change the instance data Instance instance = await _instanceRepository.GetOneAsync(instanceId, instanceOwnerId); if (instance == null) { return(NotFound("Provided instanceId is unknown to platform storage service")); } // check that data element exists, if not raise exception if (instance.Data != null && instance.Data.ContainsKey(formId)) { Dictionary <string, Data> formData = instance.Data[formId]; if (formData.ContainsKey(dataId.ToString())) { Data data = formData[dataId.ToString()]; if (data == null) { return(NotFound()); } string storageFileName = GetFileName(instanceId, formId, instance, data); if (string.Equals(data.StorageUrl, storageFileName)) { DateTime updateTime = DateTime.UtcNow; Stream theStream = null; string contentType = null; string contentFileName = null; if (MultipartRequestHelper.IsMultipartContentType(Request.ContentType)) { // Only read the first section of the mulitpart message. MediaTypeHeaderValue mediaType = MediaTypeHeaderValue.Parse(Request.ContentType); string boundary = MultipartRequestHelper.GetBoundary(mediaType, _defaultFormOptions.MultipartBoundaryLengthLimit); MultipartReader reader = new MultipartReader(boundary, Request.Body); MultipartSection section = await reader.ReadNextSectionAsync(); theStream = section.Body; contentType = section.ContentType; ContentDispositionHeaderValue contentDisposition; bool hasContentDisposition = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out contentDisposition); if (hasContentDisposition) { contentFileName = contentDisposition.FileName.ToString(); } } else { theStream = Request.Body; contentType = Request.ContentType; } if (theStream == null) { return(BadRequest("No data attachements found")); } DateTime changedTime = DateTime.UtcNow; // update data record data.ContentType = contentType; data.FileName = contentFileName; data.LastChangedBy = User.Identity.Name; data.LastChangedDateTime = changedTime; instance.LastChangedDateTime = changedTime; instance.LastChangedBy = 0; // store file as blob bool success = await _dataRepository.UpdateDataInStorage(theStream, storageFileName); if (success) { // update instance Instance result = await _instanceRepository.UpdateInstanceInCollectionAsync(instanceId, instance); return(Ok(result)); } return(UnprocessableEntity()); } } } return(UnprocessableEntity()); }
/// <summary> /// Replaces the signature image. /// </summary> /// <param name='userId'> /// The id of the user whos signature image should be replaced. /// </param> /// <param name='file'> /// Upload software package /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <HttpOperationResponse <object> > UploadSignatureImageWithHttpMessagesAsync(string userId, System.IO.Stream file, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (userId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "userId"); } if (file == null) { throw new ValidationException(ValidationRules.CannotBeNull, "file"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("userId", userId); tracingParameters.Add("file", file); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "UploadSignatureImage", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "v1.0/user/{userId}/uploadSignatureImage").ToString(); _url = _url.Replace("{userId}", Uri.EscapeDataString(userId)); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; MultipartFormDataContent _multiPartContent = new MultipartFormDataContent(); if (file != null) { StreamContent _file = new StreamContent(file); _file.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); System.IO.FileStream _fileAsFileStream = file as System.IO.FileStream; if (_fileAsFileStream != null) { ContentDispositionHeaderValue _contentDispositionHeaderValue = new ContentDispositionHeaderValue("form-data"); _contentDispositionHeaderValue.Name = "File"; _contentDispositionHeaderValue.FileName = _fileAsFileStream.Name; _file.Headers.ContentDisposition = _contentDispositionHeaderValue; } _multiPartContent.Add(_file, "File"); } _httpRequest.Content = _multiPartContent; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204 && (int)_statusCode != 400 && (int)_statusCode != 401 && (int)_statusCode != 404 && (int)_statusCode != 415) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse <object>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 400) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject <object>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 404) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject <object>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 415) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject <object>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
public async Task <IActionResult> PostAppFileStream() { if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType)) { ModelState.AddModelError("File", $"The request couldn't be processed (Error 1)."); // Log error return(BadRequest(ModelState)); } // Accumulate the form data key-value pairs in the request (formAccumulator). var formAccumulator = new KeyValueAccumulator(); var trustedFileNameForDisplay = string.Empty; var untrustedFileNameForStorage = string.Empty; var streamedFileContent = new byte[0]; var boundary = MultipartRequestHelper.GetBoundary( MediaTypeHeaderValue.Parse(Request.ContentType), _defaultFormOptions.MultipartBoundaryLengthLimit); var reader = new MultipartReader(boundary, HttpContext.Request.Body); var section = await reader.ReadNextSectionAsync(); while (section != null) { var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse( section.ContentDisposition, out var contentDisposition); if (hasContentDispositionHeader) { if (MultipartRequestHelper .HasFileContentDisposition(contentDisposition)) { untrustedFileNameForStorage = contentDisposition.FileName.Value; // Don't trust the file name sent by the client. To display // the file name, HTML-encode the value. trustedFileNameForDisplay = WebUtility.HtmlEncode( contentDisposition.FileName.Value); streamedFileContent = await FileHelpers.ProcessStreamedFile(section, contentDisposition, ModelState, _permittedExtensions, _fileSizeLimit); if (!ModelState.IsValid) { return(BadRequest(ModelState)); } } else if (MultipartRequestHelper .HasFormDataContentDisposition(contentDisposition)) { // Don't limit the key name length because the // multipart headers length limit is already in effect. var key = HeaderUtilities .RemoveQuotes(contentDisposition.Name).Value; var encoding = GetEncoding(section); if (encoding == null) { ModelState.AddModelError("File", $"The request couldn't be processed (Error 2)."); // Log error return(BadRequest(ModelState)); } using (var streamReader = new StreamReader( section.Body, encoding, detectEncodingFromByteOrderMarks: true, bufferSize: 1024, leaveOpen: true)) { // The value length limit is enforced by // MultipartBodyLengthLimit var value = await streamReader.ReadToEndAsync(); if (string.Equals(value, "undefined", StringComparison.OrdinalIgnoreCase)) { value = string.Empty; } formAccumulator.Append(key, value); if (formAccumulator.ValueCount > _defaultFormOptions.ValueCountLimit) { // Form key count limit of // _defaultFormOptions.ValueCountLimit // is exceeded. ModelState.AddModelError("File", $"The request couldn't be processed (Error 3)."); // Log error return(BadRequest(ModelState)); } } } } // Drain any remaining section body that hasn't been consumed and // read the headers for the next section. section = await reader.ReadNextSectionAsync(); } // Bind form data to the model var formData = new FormData(); var formValueProvider = new FormValueProvider( BindingSource.Form, new FormCollection(formAccumulator.GetResults()), CultureInfo.CurrentCulture); var bindingSuccessful = await TryUpdateModelAsync(formData, prefix : "", valueProvider : formValueProvider); if (!bindingSuccessful) { ModelState.AddModelError("File", "The request couldn't be processed (Error 5)."); // Log error return(BadRequest(ModelState)); } // **WARNING!** // In the following example, the file is saved without // scanning the file's contents. In most production // scenarios, an anti-virus/anti-malware scanner API // is used on the file before making the file available // for download or for use by other systems. // For more information, see the topic that accompanies // this sample app. var file = new AppFile() { Content = streamedFileContent, UntrustedName = untrustedFileNameForStorage, Note = formData.Note, Size = streamedFileContent.Length, UploadDT = DateTime.UtcNow }; _context.File.Add(file); await _context.SaveChangesAsync(); return(Created($"api/AppFiles/{file.Id}", null)); }
/// <summary> /// Reads a multipart section, checks if it meets criteria of Application metadata and returns a part holding the stream with content. /// </summary> /// <param name="section">the section to read</param> /// <param name="appInfo">the application metadata</param> /// <param name="errorResult">error message</param> /// <returns>the part holding the section's stream</returns> private Part ReadSectionIntoPartOrError(MultipartSection section, Application appInfo, out ActionResult errorResult) { errorResult = null; bool hasContentDispositionHeader = ContentDispositionHeaderValue .TryParse(section.ContentDisposition, out ContentDispositionHeaderValue contentDisposition); if (!hasContentDispositionHeader) { errorResult = BadRequest("Multipart section must have content disposition header"); return(null); } if (!contentDisposition.Name.HasValue) { errorResult = BadRequest("Multipart section has no name. It must have a name that corresponds to elementTypes defined in Application metadat"); return(null); } string sectionName = contentDisposition.Name.Value; string contentType = section.ContentType; if (sectionName.Equals("instance")) { Part part = ReadInstanceTemplatePart(contentType, section.Body, out ActionResult instanceTemplateError); if (instanceTemplateError != null) { errorResult = instanceTemplateError; return(null); } if (part != null) { return(part); } } else { // Check if the section name is declared for the application (e.g. "default"). ElementType elementType = appInfo.ElementTypes.Find(e => e.Id == sectionName); if (elementType == null) { errorResult = BadRequest($"Multipart section named, '{sectionName}' does not correspond to an element type in application metadata"); return(null); } if (section.ContentType == null) { errorResult = BadRequest($"The multipart section named {sectionName} is missing Content-Type."); return(null); } string contentTypeWithoutEncoding = contentType.Split(";")[0]; // Check if the content type of the multipart section is declared for the element type (e.g. "application/xml"). if (!elementType.AllowedContentType.Contains(contentTypeWithoutEncoding)) { errorResult = BadRequest($"The multipart section named {sectionName} has a Content-Type '{contentType}' which is not declared in this application element type '{elementType}'"); return(null); } string contentFileName = contentDisposition.FileName.HasValue ? contentDisposition.FileName.Value : null; long fileSize = contentDisposition.Size ?? 0; // copy the section.Body stream since this stream cannot be rewind MemoryStream memoryStream = CopyStreamIntoMemoryStream(section.Body); if (memoryStream.Length == 0) { errorResult = BadRequest($"The multpart section named {sectionName} has no data. Cannot process empty part."); return(null); } return(new Part() { ContentType = contentType, Name = sectionName, Stream = memoryStream, FileName = contentFileName, FileSize = fileSize, }); } return(null); }
public ActionResult Uploadimg() { var result = new ResultAdaptDto(); //long size = 0; //当设置了开始水印的时候,可以使用nomark来过滤图片不加水印 int nomark = RequestHelper.GetPostInt("nomark"); var files = Request.Form.Files; if (files.Count == 0) { result.status = false; result.message = "没有文件信息"; return(Content(result.ToJson())); } string url = $"/upfiles/images/{DateTime.Now.ToString("yyyyMMdd")}"; var folder = GlobalContext.WebRootPath + url; if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } var file = files[0]; var filename = ContentDispositionHeaderValue .Parse(file.ContentDisposition) .FileName .Trim('"'); int index = filename.LastIndexOf('.'); string extName = filename.Substring(index); string guidstr = Guid.NewGuid().ToString("N"); string guidFileName = guidstr + extName; //这个hostingEnv.WebRootPath就是要存的地址可以改下 filename = $"{folder}/{guidFileName}"; using (FileStream fs = System.IO.File.Create(filename)) { file.CopyTo(fs); fs.Flush(); } var firstFileInfo = new FileInfo(filename); if (firstFileInfo.Length > 200 * 1024) { string compressFileName = IdHelper.ObjectId() + extName; string compressFile = $"{folder}/{compressFileName}"; ImageUtilities.CompressImage(filename, compressFile, 90, 200); guidFileName = compressFileName; } if (nomark == 0) { var imageSet = SiteManagerCache.GetUploadInfo(); if (imageSet.open_watermark == 1) { try { string sourcePath = $"{folder}/{guidFileName}"; if (System.IO.File.Exists(sourcePath)) { FileStream fs = new FileStream(sourcePath, FileMode.Open); //把文件读取到字节数组 byte[] data = new byte[fs.Length]; fs.Read(data, 0, data.Length); fs.Close(); //实例化一个内存流--->把从文件流中读取的内容[字节数组]放到内存流中去 MemoryStream ms = new MemoryStream(data); Image image = Image.FromStream(ms); if (image.Width > imageSet.image_width && image.Height > imageSet.image_height) { ImageWatermarker marker = new ImageWatermarker(); //图片水印 if (imageSet.watermark_type == 1) { string waterMarkIamge = GlobalContext.WebRootPath + imageSet.watermark_image; if (System.IO.File.Exists(waterMarkIamge)) { marker.AddImageSignPic(image, sourcePath, waterMarkIamge, imageSet.water_postion, imageSet.image_quality, imageSet.image_opacity); } } else { marker.AddWatermarkText(image, sourcePath, imageSet.watermark_word, imageSet.water_postion, imageSet.font_size, imageSet.font_color); } } } } catch (Exception ex) { LoggerHelper.Exception(ex); } } } string imgurl = $"{ url}/{guidFileName}"; result.data.Add("url", imgurl); return(Content(result.ToJson())); }
async Task DoFile(String url) { switch (Request.HttpMethod.ToUpperInvariant()) { case "POST": if (IsNotAjax()) { return; } Response.ContentType = "application/json"; try { var files = Request.Files; await _baseController.SaveFiles(url, files, SetQueryStringAndSqlQueryParams, Response.Output); } catch (Exception ex) { WriteExceptionStatus(ex); } break; case "GET": try { var token = Request.QueryString["token"]; if (token == null) { throw new InvalidOperationException("There is no access token for image"); } var ai = await _baseController.LoadFileGet(url, SetQueryStringAndSqlQueryParams); if (ai == null) { throw new InvalidOperationException($"Not found. Url='{url}'"); } if (!_baseController.IsTokenValid(Response, ai.Token, token)) { return; } Response.ContentType = ai.Mime; if (Request.QueryString["export"] != null) { var cdh = new ContentDispositionHeaderValue("attachment") { FileNameStar = _baseController.Localize(ai.Name) }; Response.Headers.Add("Content-Disposition", cdh.ToString()); } else { CacheImage(ai); } if (ai.Stream != null) { Response.BinaryWrite(ai.Stream); } } catch (Exception ex) { var accept = Request.Headers["Accept"]; if (accept != null && accept.Trim().StartsWith("image", StringComparison.OrdinalIgnoreCase)) { WriteImageException(ex); } else { WriteExceptionStatus(ex); } } break; } }
public async Task <ActionResult <BlobInfo[]> > UploadAssetAsync([FromQuery] string folderUrl, [FromQuery] string url = null, [FromQuery] string name = null) { // https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-3.1 if (url == null && !MultipartRequestHelper.IsMultipartContentType(Request.ContentType)) { return(BadRequest($"Expected a multipart request, but got {Request.ContentType}")); } var result = new List <BlobInfo>(); if (url != null) { var fileName = name ?? HttpUtility.UrlDecode(Path.GetFileName(url)); var fileUrl = folderUrl + "/" + fileName; using (var client = new WebClient()) using (var blobStream = _blobProvider.OpenWrite(fileUrl)) using (var remoteStream = client.OpenRead(url)) { remoteStream.CopyTo(blobStream); var blobInfo = AbstractTypeFactory <BlobInfo> .TryCreateInstance(); blobInfo.Name = fileName; blobInfo.RelativeUrl = fileUrl; blobInfo.Url = _urlResolver.GetAbsoluteUrl(fileUrl); result.Add(blobInfo); } } else { var boundary = MultipartRequestHelper.GetBoundary(MediaTypeHeaderValue.Parse(Request.ContentType), _defaultFormOptions.MultipartBoundaryLengthLimit); var reader = new MultipartReader(boundary, HttpContext.Request.Body); var section = await reader.ReadNextSectionAsync(); if (section != null) { var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var contentDisposition); if (hasContentDispositionHeader) { if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition)) { var fileName = contentDisposition.FileName.Value; var targetFilePath = folderUrl + "/" + fileName; using (var targetStream = _blobProvider.OpenWrite(targetFilePath)) { await section.Body.CopyToAsync(targetStream); } var blobInfo = AbstractTypeFactory <BlobInfo> .TryCreateInstance(); blobInfo.Name = fileName; blobInfo.RelativeUrl = targetFilePath; blobInfo.Url = _urlResolver.GetAbsoluteUrl(targetFilePath); blobInfo.ContentType = MimeTypeResolver.ResolveContentType(fileName); result.Add(blobInfo); } } } } return(Ok(result.ToArray())); }
public async Task PostImportAsync() { using (ContextPool.AllocateOperationContext(out DocumentsOperationContext context)) { if (HttpContext.Request.HasFormContentType == false) { HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest; // Bad request using (var writer = new BlittableJsonTextWriter(context, ResponseBodyStream())) { context.Write(writer, new DynamicJsonValue { ["Type"] = "Error", ["Error"] = "This endpoint requires form content type" }); return; } } var operationId = GetLongQueryString("operationId", false) ?? Database.Operations.GetNextOperationId(); var token = CreateOperationToken(); var result = new SmugglerResult(); await Database.Operations.AddOperation(Database, "Import to: " + Database.Name, Operations.OperationType.DatabaseImport, onProgress => { return(Task.Run(async() => { try { var boundary = MultipartRequestHelper.GetBoundary( MediaTypeHeaderValue.Parse(HttpContext.Request.ContentType), MultipartRequestHelper.MultipartBoundaryLengthLimit); var reader = new MultipartReader(boundary, HttpContext.Request.Body); DatabaseSmugglerOptionsServerSide options = null; while (true) { var section = await reader.ReadNextSectionAsync().ConfigureAwait(false); if (section == null) { break; } if (ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out ContentDispositionHeaderValue contentDisposition) == false) { continue; } if (MultipartRequestHelper.HasFormDataContentDisposition(contentDisposition)) { var key = HeaderUtilities.RemoveQuotes(contentDisposition.Name); if (key != "importOptions") { continue; } BlittableJsonReaderObject blittableJson; if (section.Headers.ContainsKey("Content-Encoding") && section.Headers["Content-Encoding"] == "gzip") { using (var gzipStream = new GZipStream(section.Body, CompressionMode.Decompress)) { blittableJson = await context.ReadForMemoryAsync(gzipStream, "importOptions"); } } else { blittableJson = await context.ReadForMemoryAsync(section.Body, "importOptions"); } options = JsonDeserializationServer.DatabaseSmugglerOptions(blittableJson); continue; } if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition) == false) { continue; } var stream = new GZipStream(section.Body, CompressionMode.Decompress); DoImportInternal(context, stream, options, result, onProgress, token); } } catch (Exception e) { result.AddError($"Error occurred during import. Exception: {e.Message}"); onProgress.Invoke(result.Progress); throw; } return (IOperationResult)result; })); }, operationId, token).ConfigureAwait(false); WriteImportResult(context, result, ResponseBodyStream()); }
public static async Task <FormValueProvider> StreamFile(this HttpRequest request, Func <FileMultipartSection, Stream> createStream) { if (!MultipartRequestHelper.IsMultipartContentType(request.ContentType)) { throw new Exception($"Expected a multipart request, but got {request.ContentType}"); } // 把 request 中的 Form 依照 Key 及 Value 存到此物件 var formAccumulator = new KeyValueAccumulator(); var boundary = MultipartRequestHelper.GetBoundary( MediaTypeHeaderValue.Parse(request.ContentType), _defaultFormOptions.MultipartBoundaryLengthLimit); var reader = new MultipartReader(boundary, request.Body); var section = await reader.ReadNextSectionAsync(); while (section != null) { // 把 Form 的欄位內容逐一取出 ContentDispositionHeaderValue contentDisposition; var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out contentDisposition); if (hasContentDispositionHeader) { if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition)) { // 若此欄位是檔案,就寫入至 Stream; using (var targetStream = createStream(section.AsFileSection())) { await section.Body.CopyToAsync(targetStream); } } else if (MultipartRequestHelper.HasFormDataContentDisposition(contentDisposition)) { // 若此欄位不是檔案,就把 Key 及 Value 取出,存入 formAccumulator var key = HeaderUtilities.RemoveQuotes(contentDisposition.Name).Value; var encoding = GetEncoding(section); using (var streamReader = new StreamReader( section.Body, encoding, detectEncodingFromByteOrderMarks: true, bufferSize: 1024, leaveOpen: true)) { var value = await streamReader.ReadToEndAsync(); if (String.Equals(value, "undefined", StringComparison.OrdinalIgnoreCase)) { value = String.Empty; } formAccumulator.Append(key, value); if (formAccumulator.ValueCount > _defaultFormOptions.ValueCountLimit) { throw new InvalidDataException($"Form key count limit {_defaultFormOptions.ValueCountLimit} exceeded."); } } } } // 取得 Form 的下一個欄位 section = await reader.ReadNextSectionAsync(); } // Bind form data to a model var formValueProvider = new FormValueProvider( BindingSource.Form, new FormCollection(formAccumulator.GetResults()), CultureInfo.CurrentCulture); return(formValueProvider); }
public async Task <IActionResult> Edit(Guid id, EditParticipantViewModel participant, IFormCollection formCollection) { if (id != participant.Id) { return(NotFound()); } if (ModelState.IsValid) { try { var participantToUpdate = await _context.Participants.FindAsync(id); participantToUpdate.LastUpdateTime = DateTime.Now; participantToUpdate.CompetitionSubjectId = participant.CompetitionSubjectId; participantToUpdate.Description = participant.Description; participantToUpdate.Subject = participant.Subject; if (formCollection.Files != null) { foreach (var file in formCollection.Files) { var fileContent = ContentDispositionHeaderValue.Parse(file.ContentDisposition); var userId = HttpContext.User.Identity.Name; // Some browsers send file names with full path. // We are only interested in the file name. var format = Path.GetExtension(fileContent.FileName.ToString().Trim('"')); var filename = Guid.NewGuid().ToString() + format; var physicalPath = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\uploads\" + userId, filename); var path = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\uploads\" + userId); bool exists = Directory.Exists(path); if (!exists) { Directory.CreateDirectory(path); } // The files are not actually saved in this demo using (var fileStream = new FileStream(physicalPath, FileMode.Create)) { await file.CopyToAsync(fileStream); } participantToUpdate.AttachedFile = filename; } } _context.Update(participantToUpdate); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ParticipantExists(participant.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(participant)); }
public async Task <IActionResult> ImportBigFile(IList <IFormFile> files) { if (files != null && files.Count > 0) { var file = files[0]; var filename = ContentDispositionHeaderValue .Parse(file.ContentDisposition) .FileName .Trim('"'); string folder = _hostingEnvironment.WebRootPath + $@"\uploaded\excels"; if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } string filePath = Path.Combine(folder, filename); using (FileStream fs = System.IO.File.Create(filePath)) { file.CopyTo(fs); fs.Flush(); } //Import ExcelPackage.LicenseContext = LicenseContext.NonCommercial; using (var package = new ExcelPackage(new FileInfo(filePath))) { ExcelWorksheet workSheet = package.Workbook.Worksheets[0]; DonationViewModel donation; await _hubContext.Clients.All.SendAsync("ShowProgress", workSheet.Dimension.End.Row); await Task.Delay(3000); for (int i = workSheet.Dimension.Start.Row + 1; i <= workSheet.Dimension.End.Row; i++) { donation = new DonationViewModel(); int.TryParse(workSheet.Cells[i, 1].Value?.ToString() ?? null, out var id); donation.id = id; int.TryParse(workSheet.Cells[i, 2].Value?.ToString() ?? null, out var parent_id); donation.parent_id = parent_id; donation.elec_code = workSheet.Cells[i, 3].Value?.ToString() ?? ""; donation.senator_id = workSheet.Cells[i, 4].Value?.ToString() ?? ""; int.TryParse(workSheet.Cells[i, 5].Value.ToString() ?? null, out var amount); donation.amount = amount; donation.representative_name = workSheet.Cells[i, 6].Value?.ToString() ?? ""; donation.postal_code = workSheet.Cells[i, 7].Value?.ToString() ?? ""; donation.address = workSheet.Cells[i, 8].Value?.ToString() ?? ""; int.TryParse(workSheet.Cells[i, 9].Value?.ToString() ?? null, out var occupation_id); donation.occupation_id = occupation_id; donation.receipt_no = workSheet.Cells[i, 10].Value?.ToString() ?? ""; _repository.Create(donation); await _hubContext.Clients.All.SendAsync("UpdateProgress", workSheet.Dimension.End.Row, i); } } return(new OkObjectResult(filePath)); } return(new NoContentResult()); }
public static bool HasFileContentDisposition(ContentDispositionHeaderValue contentDisposition) { return(contentDisposition != null && contentDisposition.DispositionType.Equals("form-data") && (!string.IsNullOrEmpty(contentDisposition.FileName.Value) || !string.IsNullOrEmpty(contentDisposition.FileNameStar.Value))); }
public async Task <PaymentNotification> Update(PaymentNotification paymentNotificationParam, IFormFile[] images) { var paymentNotification = await _context.PaymentNotifications.Where(x => x.Reference == paymentNotificationParam.Reference).FirstOrDefaultAsync(); if (paymentNotification == null) { throw new AppException("Payment notification not found"); } if (!paymentNotification.UpdateAllowed) { throw new AppException("Invalid payment notification update attempted"); } if (images != null) { for (int i = 0; i < images.Length; i++) { if (images[i] != null && images[i].Length > 0) { var file = images[i]; if (file.Length > 0) { if (!file.ContentType.StartsWith("image")) { var fileLength = file.Length / 1024; var maxFileLength = 5120; if (fileLength > maxFileLength) { throw new AppException("Uploaded file must not be more than 5MB!"); } } } } } } paymentNotification.AmountPaid = paymentNotificationParam.AmountPaid; paymentNotification.PaymentChannel = paymentNotificationParam.PaymentChannel; paymentNotification.PaymentDateAndTime = paymentNotificationParam.PaymentDateAndTime; paymentNotification.DepositorName = paymentNotificationParam.DepositorName; paymentNotification.AdditionalDetails = paymentNotificationParam.AdditionalDetails; if (images != null) { for (int i = 0; i < images.Length; i++) { Bitmap originalFile = null; Bitmap resizedFile = null; int imgWidth = 0; int imgHeigth = 0; if ((i == 0) && (images[i] != null) && (images[i].Length > 0)) { var uploads = Path.GetFullPath(Path.Combine(GlobalVariables.ImagePath, @"images\payment")); var file = images[i]; if (file.Length > 0) { var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim(); string uniqueFileName = paymentNotification.FirstName.Substring(0, 5) + i + DateTime.Now + file.FileName; string uniqueFileNameTrimmed = uniqueFileName.Replace(":", "").Replace("-", "").Replace(" ", "").Replace("/", ""); using (var fileStream = new FileStream(Path.Combine(uploads, uniqueFileNameTrimmed), FileMode.Create)) { await file.CopyToAsync(fileStream); paymentNotification.ImageNames = uniqueFileNameTrimmed; if (file.ContentType.StartsWith("image")) { int width = 200; int height = 200; originalFile = new Bitmap(fileStream); resizedFile = ResizeImage.GetResizedImage(fileStream, width, height, width, height); } } if (resizedFile != null) { imgWidth = resizedFile.Width; imgHeigth = resizedFile.Height; using (var fileStreamUp = new FileStream(Path.Combine(uploads, uniqueFileNameTrimmed), FileMode.Create)) { resizedFile.Save(fileStreamUp, ImageFormat.Jpeg); } } } } } } DateTime paymentNotificationLocalDate_Nigeria = new DateTime(); string windowsTimeZone = GetWindowsFromOlson.GetWindowsFromOlsonFunc("Africa/Lagos"); paymentNotificationLocalDate_Nigeria = TimeZoneInfo.ConvertTime(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById(windowsTimeZone)); paymentNotification.DateEdited = paymentNotificationLocalDate_Nigeria; _context.PaymentNotifications.Update(paymentNotification); await _context.SaveChangesAsync(); //ThreadPool.QueueUserWorkItem(o => { string body = "Dear " + paymentNotification.FirstName + ",<br/><br/>Thank you for updating your payment notification.<br/><br/>" + "We will check your updated payment notification and update your online profile.<br/><br/>" + "You will also receive an email from us as soon as we have taken any action on your updated payment notification<br/><br/>" + "Thanks,<br/>The RotatePay Team<br/>"; var message = new Message(new string[] { paymentNotification.Email }, "[RotatePay] Updated Payment Notification Received", body, null); _emailSenderService.SendEmail(message); string body1 = paymentNotification.FirstName + "(" + paymentNotification.Email + ") has updated their payment notification with reference " + paymentNotification.Reference + ".<br/><br/><br/>"; var message1 = new Message(new string[] { GlobalVariables.AdminEmail }, "[RotatePay] Updated Payment Notification by " + paymentNotification.Email, body1, images); _emailSenderService.SendEmail(message1); //}); //await _logService.Create(log); return(paymentNotification); }
public async Task <IActionResult> UploadFileAsync([FromRoute] int referenceID) { try { var file = Request.Form.Files[0]; string folderName = "Upload"; string webRootPath = _hostingEnvironment.WebRootPath; string newPath = Path.Combine(webRootPath, folderName); if (!Directory.Exists(newPath)) { Directory.CreateDirectory(newPath); } if (file.Length > 0) { int maxFileSize = Convert.ToInt16(_appSettings.MaxFileSize);//MB string fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"'); string fullPath = Path.Combine(newPath, fileName); Int64 fileSize = file.Length; if (fileSize > (maxFileSize * 1024 * 1024)) { return(BadRequest("Filesize of image is too large. Maximum file size permitted is " + maxFileSize + "MB")); // return Json("Filesize of image is too large. Maximum file size permitted is " + maxFileSize + "KB"); } //check that the file is of the permitted file type string fileExtension = Path.GetExtension(fileName); fileExtension = fileExtension.ToLower(); string[] acceptedFileTypes = _appSettings.AcceptedFileTypes.Split(','); bool acceptFile = false; for (int i = 0; i <= acceptedFileTypes.Length - 1; i++) { if (fileExtension == acceptedFileTypes[i]) { acceptFile = true; break; } } if (!acceptFile) { return(BadRequest("The file you are trying to upload is not a permitted file type!")); //return Json("The file you are trying to upload is not a permitted file type!"); } var fiName = Guid.NewGuid().ToString() + Path.GetExtension(fileName); byte[] p1 = null; if (_appSettings.UploadFileToDataBase == "0") { using (var stream = new FileStream(Path.Combine(newPath, fiName), FileMode.Create))//حفظ الملف في upload { file.CopyTo(stream); } } else { using (var fs1 = file.OpenReadStream()) using (var ms1 = new MemoryStream()) { fs1.CopyTo(ms1); p1 = ms1.ToArray(); } } Attachment blog = new Attachment { ReferenceID = referenceID, FileContent = p1, FileType = GetContentType(fullPath), FileName = fiName }; var obj = await _attachmentRepository.SaveAttachment(blog); string json = JsonConvert.SerializeObject(new { results = new Result { attachmentID = obj.AttachmentID, fileName = fiName, message = "Upload Successful." } }); return(Ok(json)); //return Json(json); } return(Ok("Upload Successful.")); // //return Json("Upload Successful."); } catch (System.Exception ex) { return(BadRequest("Upload Failed: " + ex.Message)); //return Json("Upload Failed: " + ex.Message); } }
/// <summary> /// 保存商品图片 /// </summary> /// <param name="goodsType"></param> /// <param name="picType"></param> /// <param name="files"></param> /// <param name="hostingEnvironment"></param> internal void SaveGoodsFiles(int goodsType, int picType, IFormFileCollection files, IHostingEnvironment hostingEnvironment) { long size = 0; foreach (var file in files) { var filename = ContentDispositionHeaderValue .Parse(file.ContentDisposition) .FileName .Trim('"'); string saveDir = $@"{ConstantProperty.BaseDir}{ConstantProperty.GoodsImagesDir}"; string dbSaveDir = $@"{ConstantProperty.GoodsImagesDir}"; if (!Directory.Exists(saveDir)) { Directory.CreateDirectory(saveDir); } string exString = filename.Substring(filename.LastIndexOf(".")); string saveName = Guid.NewGuid().ToString("N"); filename = $@"{saveDir}{saveName}{exString}"; size += file.Length; FileModel<string[]> fileCard = new FileModel<string[]>(); using (FileStream fs = System.IO.File.Create(filename)) { file.CopyTo(fs); fs.Flush(); string[] fileUrls = new string[] { $@"{dbSaveDir}{saveName}{exString}" }; } var goodsPicCollection = mongo.GetMongoCollection<GoodsPic>(); var goodsPic = goodsPicCollection.Find(x => x.GoodsClass == (GoodsClass)goodsType).FirstOrDefault(); if (goodsPic == null) { goodsPic = new GoodsPic() { GoodsClass = (GoodsClass)goodsType }; goodsPicCollection.InsertOne(goodsPic); } if (goodsPic.HeaderPics == null) { goodsPicCollection.UpdateOne(x => x.GoodsPicID.Equals(goodsPic.GoodsPicID), Builders<GoodsPic>.Update.Set(x => x.HeaderPics, new List<FileModel<string[]>>())); } if (goodsPic.BodyPics == null) { goodsPicCollection.UpdateOne(x => x.GoodsPicID.Equals(goodsPic.GoodsPicID), Builders<GoodsPic>.Update.Set(x => x.BodyPics, new List<FileModel<string[]>>())); } ParamsCreate3Img params3Img = new ParamsCreate3Img() { FileName = filename, FileDir = ConstantProperty.GoodsImagesDir }; params3Img.OnFinish += fileModel => { fileModel.FileID = ObjectId.GenerateNewId(); if (picType == 0) { var update = Builders<GoodsPic>.Update.Push(x => x.HeaderPics, fileModel); goodsPicCollection.UpdateOne(x => x.GoodsPicID.Equals(goodsPic.GoodsPicID), update); } else { var update = Builders<GoodsPic>.Update.Push(x => x.BodyPics, fileModel); goodsPicCollection.UpdateOne(x => x.GoodsPicID.Equals(goodsPic.GoodsPicID), update); } mongo.GetMongoCollection<FileModel<string[]>>("FileModel").InsertOne(fileModel); }; //ThreadPool.QueueUserWorkItem(new WaitCallback(ImageTool.Create3Img), params3Img); new Thread(new ParameterizedThreadStart(ImageTool.Create3Img)).Start(params3Img); } }
public async Task <IActionResult> EditPost(int?id, IList <IFormFile> _files) { if (id == null) { return(NotFound()); } var souvenirToUpdate = await _context.Souvenirs.SingleOrDefaultAsync(s => s.SouvenirID == id); var relativeName = ""; var fileName = ""; if (_files.Count < 1) { relativeName = souvenirToUpdate.PhotoPath; } else { foreach (var file in _files) { fileName = ContentDispositionHeaderValue .Parse(file.ContentDisposition) .FileName .Trim('"'); //Path for localhost relativeName = "/images/SouvenirImages/" + DateTime.Now.ToString("ddMMyyyy-HHmmssffffff") + fileName; using (FileStream fs = System.IO.File.Create(_hostingEnv.WebRootPath + relativeName)) { await file.CopyToAsync(fs); fs.Flush(); } } } souvenirToUpdate.PhotoPath = relativeName; if (await TryUpdateModelAsync <Souvenir>( souvenirToUpdate, "", s => s.SouvenirName, s => s.Price, s => s.PhotoPath, s => s.PhotoPath, s => s.Description, s => s.CategoryID, s => s.SupplierID)) { try { await _context.SaveChangesAsync(); ViewData["CategoryID"] = new SelectList(_context.Categories, "CategoryID", "CategoryID", souvenirToUpdate.CategoryID); ViewData["SupplierID"] = new SelectList(_context.Suppliers, "SupplierID", "SupplierID", souvenirToUpdate.SupplierID); return(RedirectToAction(nameof(Index))); } catch (DbUpdateException /* ex */) { //Log the error (uncomment ex variable name and write a log.) ModelState.AddModelError("", "Unable to save changes. " + "Try again, and if the problem persists, " + "see your system administrator."); } } return(View(souvenirToUpdate)); }
/// <summary> /// Stream a file /// </summary> /// <param name="request">The request</param> /// <param name="targetStream">The target stream</param> /// <returns></returns> public static async Task <FormValueProvider> StreamFile(this HttpRequest request, Stream targetStream) { if (!MultipartRequestHelper.IsMultipartContentType(request.ContentType)) { throw new Exception($"Expected a multipart request, but got {request.ContentType}"); } // Used to accumulate all the form url encoded key value pairs in the // request. KeyValueAccumulator formAccumulator = default(KeyValueAccumulator); string boundary = MultipartRequestHelper.GetBoundary( MediaTypeHeaderValue.Parse(request.ContentType), _defaultFormOptions.MultipartBoundaryLengthLimit); MultipartReader reader = new MultipartReader(boundary, request.Body); MultipartSection section = await reader.ReadNextSectionAsync(); while (section != null) { ContentDispositionHeaderValue contentDisposition; bool hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out contentDisposition); if (hasContentDispositionHeader) { if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition)) { await section.Body.CopyToAsync(targetStream); } else if (MultipartRequestHelper.HasFormDataContentDisposition(contentDisposition)) { // Content-Disposition: form-data; name="key" // // value // Do not limit the key name length here because the // multipart headers length limit is already in effect. StringSegment key = HeaderUtilities.RemoveQuotes(contentDisposition.Name); Encoding encoding = GetEncoding(section); using (StreamReader streamReader = new StreamReader( section.Body, encoding, detectEncodingFromByteOrderMarks: true, bufferSize: 1024, leaveOpen: true)) { // The value length limit is enforced by MultipartBodyLengthLimit string value = await streamReader.ReadToEndAsync(); if (string.Equals(value, "undefined", StringComparison.OrdinalIgnoreCase)) { value = string.Empty; } formAccumulator.Append(key.Value, value); // For .NET Core <2.0 remove ".Value" from key if (formAccumulator.ValueCount > _defaultFormOptions.ValueCountLimit) { throw new InvalidDataException($"Form key count limit {_defaultFormOptions.ValueCountLimit} exceeded."); } } } } // Drains any remaining section body that has not been consumed and // reads the headers for the next section. section = await reader.ReadNextSectionAsync(); } // Bind form data to a model FormValueProvider formValueProvider = new FormValueProvider( BindingSource.Form, new FormCollection(formAccumulator.GetResults()), CultureInfo.CurrentCulture); return(formValueProvider); }
public void ProcessParameter(HttpRequestMessageBuilder requestBuilder, ParameterInfo parameterInfo, object parameterValue) { Action <object> process = (pv) => { HttpContent content = null; if (pv is HttpContent) { content = pv as HttpContent; } else { var dispositionName = "\"" + (!string.IsNullOrWhiteSpace(this.Name) ? this.Name : parameterInfo.Name) + "\""; var contentDisposition = new ContentDispositionHeaderValue( requestBuilder.MultiPartAttribute != null ? requestBuilder.MultiPartAttribute.MultiPartType : MultiPartType.FormData ); if (pv is Stream) { var s = pv as Stream; content = new StreamContent(s); } else if (pv is IEnumerable <byte> ) { var s = new MemoryStream((pv as IEnumerable <byte>).ToArray()); content = new StreamContent(s); } else { var val = Convert.ToString(pv); content = new StringContent(val); } if (!string.IsNullOrWhiteSpace(this.ContentType)) { content.Headers.ContentType = new MediaTypeHeaderValue(this.ContentType); } content.Headers.ContentDisposition = contentDisposition; content.Headers.ContentDisposition.Name = dispositionName; } requestBuilder.RawContents.Add(content); }; if (parameterValue != null) { if (typeof(IEnumerable).IsAssignableFrom(parameterValue.GetType())) { foreach (var pv in parameterValue as IEnumerable) { process(pv); } } else if (parameterValue.GetType().IsArray) { foreach (var pv in parameterValue as Array) { process(pv); } } else { process(parameterValue); } } else { throw new NotSupportedException("parameterValue not allow null"); } }
private bool HasFileContentDisposition(ContentDispositionHeaderValue contentDisposition) { // Content-Disposition: form-data; name="myfile1"; filename="Misc 002.jpg" return(contentDisposition != null && contentDisposition.DispositionType.Equals("form-data") && (!StringSegment.IsNullOrEmpty(contentDisposition.FileName) || !StringSegment.IsNullOrEmpty(contentDisposition.FileNameStar))); }
public async Task <IActionResult> Upload() { try { if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType)) { return(BadRequest($"Expected a multipart request, but got {Request.ContentType}")); } // Used to accumulate all the form url encoded key value pairs in the request. var formAccumulator = new KeyValueAccumulator(); string targetFilePath = null; var boundary = MultipartRequestHelper.GetBoundary(MediaTypeHeaderValue.Parse(Request.ContentType), DefaultFormOptions.MultipartBoundaryLengthLimit); var reader = new MultipartReader(boundary, HttpContext.Request.Body); var section = await reader.ReadNextSectionAsync(); while (section != null) { var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var contentDisposition); if (hasContentDispositionHeader) { if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition)) { targetFilePath = Path.GetTempFileName(); using (var targetStream = System.IO.File.Create(targetFilePath)) { await section.Body.CopyToAsync(targetStream); _logger.LogInformation($"Copied the uploaded file '{targetFilePath}'"); } } else if (MultipartRequestHelper.HasFormDataContentDisposition(contentDisposition)) { // Do not limit the key name length here because the // multipart headers length limit is already in effect. var key = HeaderUtilities.RemoveQuotes(contentDisposition.Name); var encoding = GetEncoding(section); using (var streamReader = new StreamReader(section.Body, encoding, true, 1024, true)) { // The value length limit is enforced by MultipartBodyLengthLimit var value = await streamReader.ReadToEndAsync(); if (string.Equals(value, "undefined", StringComparison.OrdinalIgnoreCase)) { value = string.Empty; } formAccumulator.Append(key.ToString(), value); if (formAccumulator.ValueCount > DefaultFormOptions.ValueCountLimit) { throw new InvalidDataException($"Form key count limit {DefaultFormOptions.ValueCountLimit} exceeded."); } } } } // Drains any remaining section body that has not been consumed and reads the headers for the next section. section = await reader.ReadNextSectionAsync(); } if (string.IsNullOrEmpty(targetFilePath) || !System.IO.File.Exists(targetFilePath)) { _logger.LogError("File not created!"); return(StatusCode(500, "Internal server error")); } // Import the file Stopwatch sw = new Stopwatch(); sw.Start(); await _fileImport.ImportAsync(targetFilePath); sw.Stop(); TimeSpan ts = sw.Elapsed; _logger.LogInformation(string.Format("Import run time: {0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10)); return(Ok(true)); } catch (Exception ex) { _logger.LogError(ex.Message); return(StatusCode(500, "Internal server error")); } }
private bool HasFormDataContentDisposition(ContentDispositionHeaderValue contentDisposition) { // Content-Disposition: form-data; name="key"; return(contentDisposition != null && contentDisposition.DispositionType.Equals("form-data") && StringSegment.IsNullOrEmpty(contentDisposition.FileName) && StringSegment.IsNullOrEmpty(contentDisposition.FileNameStar)); }
public async Task <IActionResult> r2addObjUnitCode() { try { var model = JsonConvert.DeserializeObject <VB_QT_VanBanMoiSoHoa>(Request.Form["model"]); VB_QT_VanBanMoiSoHoa objvb = new VB_QT_VanBanMoiSoHoa(); var userId = Convert.ToInt32(User.Claims.First(c => c.Type == "UserId").Value); var user = await _context.Sys_Dm_User.FindAsync(userId); var userNguoiKy = await _context.Sys_Dm_User.FirstOrDefaultAsync(x => x.Id == model.NguoiKyId); if (model != null) { objvb.Id = Helper.GenKey(); objvb.CompanyId = user.CompanyId ?? 0; objvb.DepartmentId = user.DepartmentId ?? 0; objvb.TenNguoiKy = userNguoiKy.FullName; objvb.LinhVucId = model.LinhVucId; objvb.LoaiVanBanId = model.LoaiVanBanId; objvb.SoKyHieu = model.SoKyHieu; objvb.NoiBanHanh = model.NoiBanHanh; objvb.NgayBanHanh = model.NgayBanHanh; objvb.TuKhoa = model.TuKhoa; objvb.SoTrang = model.SoTrang; objvb.SoTrang = model.SoTrang; objvb.TenNguoiTao = user.FullName; objvb.CreateDate = DateTime.Now; objvb.UserCreateId = userId; objvb.TrichYeu = model.TrichYeu; _context.VB_QT_VanBanMoiSoHoa.Add(objvb); } VB_QT_LuanChuyenVanBan lcvb = LuanChuyenVanBan.r2AddLuanChuyenVanBan(objvb.Id, userId, user.FullName, userId, user.FullName, "", "", false, null, null, 1, "VB_MOISOHOA", DateTime.Now, false, null, "VB0101", "VB0101", user.PositionName, user.PositionName, user.DepartmentName, user.DepartmentName); _context.VB_QT_LuanChuyenVanBan.Add(lcvb); if (Request.Form.Files.Count != 0) { foreach (var item in Request.Form.Files) { VB_QT_FileVBMoiSoHoa obj = new VB_QT_FileVBMoiSoHoa(); var file = item; var folderName = Path.Combine("Resources", "VanBan"); var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName); if (!Directory.Exists(pathToSave)) { Directory.CreateDirectory(pathToSave); } if (model != null) { if (file.Length > 0) { var fileName = long.Parse(DateTime.Now.ToString("yyyyMMddHHmmss")).ToString() + ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"'); var fullPath = Path.Combine(pathToSave, fileName); var dbPath = Path.Combine(folderName, fileName); obj.Path = dbPath; using (var stream = new FileStream(fullPath, FileMode.Create)) { file.CopyTo(stream); } } } obj.Name = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"'); obj.VbMoiSoHoaId = objvb.Id; obj.Size = file.Length; obj.Type = 1; _context.VB_QT_FileVBMoiSoHoa.Add(obj); } } await _context.SaveChangesAsync(); return(new ObjectResult(new { error = 0, ms = "" }));; } catch (Exception ex) { var result = new OkObjectResult(new { error = 1, ms = "Lỗi khi thêm mới UnitCode, vui lòng kiểm tra lại!" }); return(result); } }