public async Task <HttpResponseMessage> UploadChunk() { var response = new HttpResponseMessage { StatusCode = HttpStatusCode.Created }; try { if (!Request.Content.IsMimeMultipartContent("form-data")) { response.StatusCode = HttpStatusCode.BadRequest; response.Content = new StringContent("No file uploaded or MIME multipart content not as expected!"); throw new HttpResponseException(response); } var meta = new DzMeta(HttpContext.Current.Request.Form); var chunkDirBasePath = HttpContext.Current.Server.MapPath("~/App_Data/"); var path = $@"{chunkDirBasePath}\{meta.dzIdentifier}"; var filename = $@"{meta.dzFilename}.{(meta.intChunkNumber + 1).ToString().PadLeft(4, '0')}.{meta.dzTotalChunks.PadLeft(4, '0')}.tmp"; Directory.CreateDirectory(path); Request.Content.LoadIntoBufferAsync().GetAwaiter().GetResult(); await Request.Content.ReadAsMultipartAsync(new CustomMultipartFormDataStreamProvider(path, filename)) .ContinueWith((task) => { if (task.IsFaulted || task.IsCanceled) { response.StatusCode = HttpStatusCode.InternalServerError; response.Content = new StringContent("Chunk upload task is faulted or canceled!"); throw new HttpResponseException(response); } }); } catch (HttpResponseException ex) { // nothing } catch (Exception ex) { response.StatusCode = HttpStatusCode.InternalServerError; response.Content = new StringContent($"Error uploading/saving chunk to filesystem: {ex.Message}"); } return(response); }
public async Task <HttpResponseMessage> UploadFile() { HttpResponseMessage response = new HttpResponseMessage { StatusCode = HttpStatusCode.Created }; try { if (!Request.HasFormContentType) { //No Files uploaded response.StatusCode = HttpStatusCode.BadRequest; response.Content = new StringContent("No file uploaded or MIME multipart content not as expected!"); throw new HttpResponseException(response); } Request.EnableBuffering(); var meta = new DzMeta(HttpContext.Request.Form); var chunkDirBasePath = Path.Combine(_env.ContentRootPath, "App_Data"); var path = string.Format(@"{0}\{1}", chunkDirBasePath, meta.dzIdentifier); var filename = string.Format(@"{0}.{1}.{2}.tmp", meta.dzFilename, (meta.intChunkNumber + 1).ToString().PadLeft(4, '0'), meta.dzTotalChunks.PadLeft(4, '0')); Directory.CreateDirectory(path); var files = Request.Form.Files; using (var stream = new FileStream(Path.Combine(path, filename), FileMode.Create)) { await files[0].CopyToAsync(stream); } } catch (HttpResponseException ex) { HelperFunctions.Log(_context, PublicEnums.LogLevel.LEVEL_EXCEPTION, "Controllers.ApiFileShareController.UploadFile", ex.Message, User, ex); } catch (Exception ex) { HelperFunctions.Log(_context, PublicEnums.LogLevel.LEVEL_EXCEPTION, "Controllers.ApiFileShareController.UploadFile", "Error uploading/saving chunk to file system", User, ex); response.StatusCode = HttpStatusCode.InternalServerError; response.Content = new StringContent(string.Format("Error uploading/saving chunk to file system: {0}", ex.Message)); } return(response); }