public async Task <IActionResult> UploadFile() { if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType)) { return(BadRequest($"Expected a multipart request, but got {Request.ContentType}")); } var deviceFile = await HandleMultipartRequest(); var formData = deviceFile.formAccumulator.GetResults(); StringValues filename; bool ok = false; ok = formData.TryGetValue("filename", out filename); if (!ok) { return(BadRequest("Expected filename key")); } StringValues deviceId; ok = formData.TryGetValue("deviceId", out deviceId); if (!ok) { return(BadRequest("Expected deviceId key")); } { Core.DeviceDictionary.TryAdd(deviceId.ToString(), Core.DeviceDictionary.Count); Core.SaveDeviceDictionaryToFile(); } { string strDeviceId = ""; int id; if (Core.DeviceDictionary.TryGetValue(deviceId.ToString(), out id)) { strDeviceId = id.ToString(); } string strfilename = filename.ToString(); Core.MakeDeviceFolder(strDeviceId); var gzipFilePath = Path.Combine(Core.DeviceGzipFolderPath(strDeviceId), strfilename); using (var stream = new FileStream(gzipFilePath, FileMode.Create)) { await deviceFile.memoryStream.CopyToAsync(stream); deviceFile.memoryStream.Close(); } var gzipFileInfo = new FileInfo(gzipFilePath); var decompressedPath = gzipFilePath.Remove((int)(gzipFileInfo.FullName.Length - gzipFileInfo.Extension.Length)); { // Decompression Test using (var compressedStream = new FileStream(gzipFilePath, FileMode.Open)) { using (var decompressedFileStream = new FileStream(decompressedPath, FileMode.Create)) { using (var decompressionStream = new GZipStream(compressedStream, CompressionMode.Decompress)) { decompressionStream.CopyTo(decompressedFileStream); } } } } { // Convert Decompressed File to ogg and add to playlist var process = new Process(); process.StartInfo.FileName = "ffmpeg"; var decompressedFileInfo = new FileInfo(decompressedPath); var filenameNoExtension = decompressedFileInfo.Name.Remove((int)(decompressedFileInfo.Name.Length - decompressedFileInfo.Extension.Length)); // var milliseconds = long.Parse(filenameNoExtension); // var date = DateTimeExtensions.DateTimeFromMilliseconds(milliseconds); // var localDate = date.ToLocalTime(); var oggFilename = filenameNoExtension + ".ogg"; var oggFilePath = Path.Combine(Core.DeviceOggFolderPath(strDeviceId), oggFilename); process.StartInfo.Arguments = "-i " + decompressedPath + " " + oggFilePath; process.Start(); } } return(Content("File received")); }
public async Task <DeviceFile> HandleMultipartRequest() { var deviceFile = new DeviceFile(); 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) { ContentDispositionHeaderValue contentDisposition; var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out contentDisposition); if (hasContentDispositionHeader) { if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition)) { await section.Body.CopyToAsync(deviceFile.memoryStream); deviceFile.memoryStream.Seek(0, SeekOrigin.Begin); } 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. var key = HeaderUtilities.RemoveQuotes(contentDisposition.Name); var encoding = GetEncoding(section); 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; } deviceFile.formAccumulator.Append(key.Value, value); if (deviceFile.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(); } return(deviceFile); }
public async Task <IActionResult> UploadFile() { if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType)) { return(BadRequest($"Expected a multipart request, but got {Request.ContentType}")); } var stationFile = await HandleMultipartRequest(); var formData = stationFile.formAccumulator.GetResults(); StringValues filename; bool ok = false; //Cuando se envian los audios se envia el APIKey con ese obtener el id y guardar en la base //APIKey para autenticar StringValues APIKey; StringValues Id; ok = formData.TryGetValue("APIKey", out APIKey); if (!ok) { return(BadRequest("Expected APIKey key")); } ok = formData.TryGetValue("Id", out Id); if (!ok) { return(BadRequest("Expected ID key")); } { string strStationId = ""; int id; var StationResult = _StationRepository.Get(APIKey.ToString()); var stationCount = _StationRepository.GetStationCount(APIKey); if (stationCount != 0) { id = StationResult.Result.Id; strStationId = id.ToString(); //id 1 2 3 //string name=StationResult.Result.Name; //name folder with station name //Authentication if (strStationId != Id) { return(BadRequest("Authentication Failed")); } //other parameters ok = formData.TryGetValue("filename", out filename); if (!ok) { return(BadRequest("Expected filename key")); } StringValues recordingDate; ok = formData.TryGetValue("RecordingDate", out recordingDate); if (!ok) { return(BadRequest("Expected RecordingDate key")); } StringValues duration; ok = formData.TryGetValue("Duration", out duration); if (!ok) { return(BadRequest("Expected Duration key")); } StringValues format; ok = formData.TryGetValue("Format", out format); if (!ok) { return(BadRequest("Expected Format key")); } var audio = new Audio(); try { audio.RecordingDate = DateTime.ParseExact(recordingDate, "d/M/yyyy HH:mm", CultureInfo.InvariantCulture); } catch (Exception ex) { return(BadRequest("Expected date to be in format 'dd/mm/yyyy hh:mm'")); } audio.ArriveDate = DateTime.Now; audio.StationId = id; audio.Duration = duration; audio.Format = format; audio.LabelList = new List <String>(); await _AudioRepository.Add(audio); var new_audio = await _AudioRepository.GetLastAudio(); string strfilename = "" + new_audio.Id + "." + new_audio.Format; var filePath = ""; if (strStationId != null) { Core.MakeStationFolder(strStationId); filePath = Path.Combine(Core.StationAudiosFolderPath(strStationId), strfilename); Console.Write(filePath); } using (var stream = new FileStream(filePath, FileMode.Create)) { await stationFile.memoryStream.CopyToAsync(stream); stationFile.memoryStream.Close(); } { // Convert Decompressed File to ogg and add to playlist var process = new Process(); process.StartInfo.FileName = "ffmpeg"; var fileInfo = new FileInfo(filePath); var filenameNoExtension = fileInfo.Name.Remove((int)(fileInfo.Name.Length - fileInfo.Extension.Length)); // var milliseconds = long.Parse(filenameNoExtension); // var date = DateTimeExtensions.DateTimeFromMilliseconds(milliseconds); // var localDate = date.ToLocalTime(); var oggFilename = filenameNoExtension + ".ogg"; var oggFilePath = Path.Combine(Core.StationOggFolderPath(strStationId), oggFilename); process.StartInfo.Arguments = "-i " + filePath + " " + oggFilePath; process.Start(); } } else { return(Content("Invalid APIKEY")); } } return(Content("File received")); }