public void update(FileUploadDto fileUploadDto) { try { _transactionManager.beginTransaction(); var file = _fileUploadRepo.getById(fileUploadDto.file_upload_id); if (file == null) { throw new ItemNotFoundException($"File with id {fileUploadDto.file_upload_id} doesnot exist."); } string oldFile = file.file_name; _fileUploadMaker.copy(ref file, fileUploadDto); _fileUploadRepo.update(file); if (!string.IsNullOrWhiteSpace(fileUploadDto.file_name)) { if (!string.IsNullOrWhiteSpace(oldFile)) { deleteImage(oldFile); } } _transactionManager.commitTransaction(); } catch (Exception) { _transactionManager.rollbackTransaction(); throw; } }
public async Task <ActionResult <dynamic> > UploadProfileImage([FromBody] FileUploadDto fileUploadModel) { if (fileUploadModel == null) { return(BadRequest("Imagem não foi enviada!")); } try { var users = await _repoWrapper.User.FindAllAsync(); if (users == null || users.Count() <= 0) { return(NotFound(new { message = "Usuário ou senha inválidos!" })); } var userDefault = users.FirstOrDefault(); if (userDefault != null) { userDefault.ImageBaseData = fileUploadModel.ImageBaseData; await _repoWrapper.User.Update(userDefault); await _repoWrapper.SaveAsync(); return(Ok(true)); } return(BadRequest("User Not Found")); } catch (Exception ex) { return(StatusCode(500, "Internal Server Error: " + ex.Message)); } }
public FileDto Upload(FileUploadDto dto) { var jwtResult = this._fileAuthService.VerifyJwt(dto.Auth); this._fileDomainService.Create(new FileCreateBo()); throw new NotImplementedException(); }
public IActionResult add(FileUploadModel model, IFormFile file) { try { if (file == null) { throw new CustomException("File must be provided."); } if (ModelState.IsValid) { FileUploadDto fileUploadDto = new FileUploadDto(); fileUploadDto.title = model.title; fileUploadDto.file_name = _fileHelper.saveFileAndGetFileName(file, model.title); fileUploadDto.description = model.description; fileUploadDto.is_enabled = model.is_enabled; _fileUploadService.save(fileUploadDto); AlertHelper.setMessage(this, "File saved successfully.", messageType.success); return(RedirectToAction("index")); } } catch (Exception ex) { AlertHelper.setMessage(this, ex.Message, messageType.error); } return(View(model)); }
public async Task <NewsPhotoForReturnDto> Create(FileUploadDto uploadDto) { var checkAnnounceById = await newsDal.GetAsync(x => x.Id == uploadDto.AnnounceId); if (checkAnnounceById == null) { throw new RestException(HttpStatusCode.BadRequest, new { NotFound = Messages.NotFoundAnnounce }); } var uploadFile = new UploadedFileResultDto(); if (uploadDto.FileType.ToLower() == "image") { uploadFile = await upload.Upload(uploadDto.File, "news"); } var mapForCreate = new NewsPhotoForCreationDto(); mapForCreate.Name = uploadFile.Name; mapForCreate.FullPath = uploadFile.FullPath; mapForCreate.NewsId = uploadDto.AnnounceId; mapForCreate.FileType = uploadFile.FileType; mapForCreate.IsConfirm = false; mapForCreate.UnConfirm = false; var mapForDb = mapper.Map <NewsPhoto>(mapForCreate); var createPhoto = await newsPhotoDal.Add(mapForDb); return(mapper.Map <NewsPhoto, NewsPhotoForReturnDto>(createPhoto)); }
public IActionResult edit(FileUploadModel model, IFormFile file) { try { if (ModelState.IsValid) { FileUploadDto fileUploadDto = new FileUploadDto(); fileUploadDto.file_upload_id = model.file_upload_id; fileUploadDto.title = model.title; fileUploadDto.description = model.description; if (file != null) { fileUploadDto.file_name = _fileHelper.saveFileAndGetFileName(file, model.title); } fileUploadDto.is_enabled = model.is_enabled; _fileUploadService.update(fileUploadDto); return(RedirectToAction("index")); } } catch (Exception ex) { AlertHelper.setMessage(this, ex.Message, messageType.error); } return(View(model)); }
public async Task <HomeAnnouncePhotoForReturnDto> CreateForPublicAsync(FileUploadDto uploadDto) { var checkAnnounceById = await homeAnnounceDal.GetAsync(x => x.Id == uploadDto.AnnounceId); var claimId = int.Parse(httpContextAccessor.HttpContext.User?.Claims?.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier)?.Value); if (claimId != checkAnnounceById.UserId) { throw new RestException(HttpStatusCode.BadRequest, new { AlreadyExist = Messages.OperationDenied }); } if (checkAnnounceById == null) { throw new RestException(HttpStatusCode.BadRequest, new { NotFound = Messages.HomeAnnounceEmpty }); } var uploadFile = await upload.Upload(uploadDto.File, "homeannounce"); var mapForCreate = new HomeAnnouncePhotoForCreationDto(); mapForCreate.Name = uploadFile.Name; mapForCreate.FullPath = uploadFile.FullPath; mapForCreate.HomeAnnounceId = uploadDto.AnnounceId; mapForCreate.IsConfirm = false; var mapForDb = mapper.Map <HomeAnnouncePhoto>(mapForCreate); var createPhoto = await homeAnnouncePhotoDal.Add(mapForDb); return(mapper.Map <HomeAnnouncePhoto, HomeAnnouncePhotoForReturnDto>(createPhoto)); }
public BusinessResult <string> Upload(FileUploadDto file) { try { string ext = Path.GetExtension(file.fileName); var split = file.Base.Split(','); string fullPath = string.Empty; if (file.AllowedExtensions.FirstOrDefault(c => c.ToLower() == ext.ToLower()) != null) { string fileName = Guid.NewGuid().ToString().Replace("-", ""); DirectoryInfo di = Directory.CreateDirectory(System.Web.Hosting.HostingEnvironment.MapPath(file.SavePath)); var bytes = Convert.FromBase64String(string.Empty); if (split.Length > 1) { bytes = Convert.FromBase64String(split[1]); } fullPath = $"{di.FullName}/{fileName}{ext}"; using (var imageFile = new FileStream(fullPath, FileMode.Create)) { imageFile.Write(bytes, 0, bytes.Length); imageFile.Flush(); } return(BusinessResult <string> .Sucess($"{file.SavePath}/{fileName}{ext}", string.Empty)); } return(BusinessResult <string> .Issue(string.Empty, $"Archivo no permitido", null)); } catch (Exception ex) { return(BusinessResult <string> .Issue(string.Empty, $"Error subiendo el archivo {file.fileName} al servidor", ex)); } }
public async Task <ActionResult <UserPhotoForReturnDto> > Create([FromForm] FileUploadDto uploadDto) { var photo = await userPhotoService.Create(uploadDto); await hubContext.Clients.Group("User").SendAsync("ReceiveNewUserProfilePhoto", photo); return(photo); }
private Maybe <string> CheckFileExists(FileUploadDto dto) { var filePath = StringUtils.GetFilePath(dto.SiteId, dto.File.FileName); var fullFilePath = Path.Combine(fileStoreSettings.BasePath, filePath); return(File.Exists(fullFilePath) ? StringUtils.ConvertToUrl(filePath) : Maybe <string> .None); }
public void GivenNullFormFile_ThenThrowsArgumentNullException() { var givenTags = new[] { "pigeons", "flying rats" }; var givenMediaDto = new FileUploadDto(givenTags, SampleUploadDate, false); Action act = () => FileUploadCommand.Create(null, givenMediaDto, SampleAuthorId); act.Should().Throw <ArgumentNullException>(); }
public void GivenNullTags_ThenThrowsArgumentNullException() { var givenFormFile = FormFileFactory.Create("filename1234", "file content"); var givenMediaDto = new FileUploadDto(null, SampleUploadDate, false); Action act = () => FileUploadCommand.Create(givenFormFile, givenMediaDto, SampleAuthorId); act.Should().Throw <ArgumentNullException>(); }
private Result <FileUploadDto> FillDto(FileUploadDto dto) { dto.Hash = GetMD5Hash(dto.File); dto.FileName = dto.File.FileName; dto.Length = dto.File.Length; dto.FilePath = StringUtils.GetFilePath(dto.SiteId, dto.FileName); return(Result.Ok(dto)); }
public void copy(ref FileUpload file_upload, FileUploadDto file_upload_dto) { file_upload.file_upload_id = file_upload_dto.file_upload_id; file_upload.title = file_upload_dto.title.Trim(); file_upload.description = file_upload_dto.description.Trim(); if (file_upload_dto.file_name != null) { file_upload.file_name = file_upload_dto.file_name; } file_upload.is_enabled = file_upload_dto.is_enabled; }
public ActionResult <List <string> > CheckResubmit([FromForm] FileUploadDto upload) { var problem = IsServiceAreaAuthorized(_currentUser, upload.ServiceAreaNumber); if (problem != null) { return(Unauthorized(problem)); } return(Ok(new List <string>())); }
public async Task <ActionResult <NewsPhotoForReturnDto> > Create([FromForm] FileUploadDto uploadDto) { var photo = await newsPhotoService.Create(uploadDto); var connIds = await userTracker.GetOnlineUser(); if (connIds != null && connIds.Length != 0) { await hubContext.Clients.GroupExcept("News", connIds).SendAsync("ReceiveNewsPhoto", photo, "create", true); } return(photo); }
public async Task <AnnouncePhotoForReturnDto> CreateForPublic(FileUploadDto uploadDto) { var checkAnnounceById = await announceDal.GetAsync(x => x.Id == uploadDto.AnnounceId); var claimId = int.Parse(httpContextAccessor.HttpContext.User?.Claims?.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier)?.Value); if (claimId != checkAnnounceById.UserId) { throw new RestException(HttpStatusCode.BadRequest, new { AlreadyExist = Messages.OperationDenied }); } if (checkAnnounceById == null) { throw new RestException(HttpStatusCode.BadRequest, new { NotFound = Messages.NotFoundAnnounce }); } if (checkAnnounceById.ContentType.ToLower() != uploadDto.FileType.ToLower()) { throw new RestException(HttpStatusCode.BadRequest, new { NotFound = "Lütfen duyuru tipine uygun bir dosya yükleyin" }); } var uploadFile = new UploadedFileResultDto(); if (uploadDto.FileType.ToLower() == "image") { uploadFile = await upload.Upload(uploadDto.File, "announce"); } if (uploadDto.FileType.ToLower() == "video") { uploadFile = await upload.UploadVideo(uploadDto.File, "announce"); } var mapForCreate = new AnnouncePhotoForCretionDto(); mapForCreate.Name = uploadFile.Name; mapForCreate.FullPath = uploadFile.FullPath; mapForCreate.AnnounceId = uploadDto.AnnounceId; mapForCreate.FileType = uploadFile.FileType; mapForCreate.Duration = uploadDto.Duration; mapForCreate.IsConfirm = false; mapForCreate.UnConfirm = false; var mapForDb = mapper.Map <AnnouncePhoto>(mapForCreate); var createPhoto = await announcePhotoDal.Add(mapForDb); //Make Announce IsNew True checkAnnounceById.IsNew = true; checkAnnounceById.IsPublish = false; checkAnnounceById.Reject = false; await announceDal.Update(checkAnnounceById); return(mapper.Map <AnnouncePhoto, AnnouncePhotoForReturnDto>(createPhoto)); }
public async Task <FoodMenuBgPhotoForReturnDto> Create(FileUploadDto uploadDto) { var uploadFile = await upload.Upload(uploadDto.File, "foodmenu"); var mapForCreate = new FoodMenuBgPhotoForCreationDto(); mapForCreate.Name = uploadFile.Name; mapForCreate.FullPath = uploadFile.FullPath; mapForCreate.IsSetBackground = false; var mapForDb = mapper.Map <FoodMenuBgPhoto>(mapForCreate); var createPhoto = await foodMenuBgPhotoDal.Add(mapForDb); return(mapper.Map <FoodMenuBgPhoto, FoodMenuBgPhotoForReturnDto>(createPhoto)); }
public async Task <FileDto> Upload(FileUploadDto dto) { var jwtResult = await this._fileAuthService.VerifyJwt(dto.Auth); await this._fileLimitDomainService.Check(new CheckFileLimitBo() { AppId = jwtResult.AppId, Name = dto.Name, Content = dto.Content }); var file = FileMapping(dto, jwtResult); var result = await this._fileDomainService.Create(file); return(FileDtoMapping(result)); }
public async Task <IActionResult> AddPhotoForUser(int userId, [FromForm] FileUploadDto fileUploadDto) { if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } var userFromRepo = await _repo.GetUser(userId); if (userFromRepo.PublicId != null) { DeleteFile(userFromRepo.PublicId); } var file = fileUploadDto.File; var uploadResult = new ImageUploadResult(); if (file.Length > 0) { using (var stream = file.OpenReadStream()) { var uploadParams = new ImageUploadParams() { File = new FileDescription(file.Name, stream), Folder = "User", Transformation = new Transformation() .Width(500).Height(500).Crop("fill").Gravity("face"), Overwrite = true, }; uploadResult = _cloudinary.Upload(uploadParams); } } fileUploadDto.FotoUrl = uploadResult.Uri.ToString(); fileUploadDto.PublicId = uploadResult.PublicId; var photo = _mapper.Map(fileUploadDto, userFromRepo); if (await _repo.SaveAll()) { var photoToReturn = _mapper.Map <UserForDetailedDto>(userFromRepo); return(CreatedAtRoute("GetPhoto", new { userId, id = userId }, photoToReturn)); } return(BadRequest("No se pudo agregar la foto")); }
public async Task <Result <string> > Upload(FileUploadDto dto) { var fileExists = CheckFileExists(dto); if (fileExists.HasValue) { return(Result.Ok(fileExists.Value)); } return(await FillDto(dto) .Bind(UploadFile) .Bind(Map) .Bind(SaveFileInfo) .OnFailure(LogError)); }
public void GivenMediaChangeIsSavedInDatabase_MediaChangeIsOfTypeCreate() { var givenFormFile = FormFileFactory.Create("newFile", string.Empty); var givenTags = new[] { "pigeons", "flying rats" }; var givenMediaDto = new FileUploadDto(givenTags, _givenDate, false); var givenUserId = "user"; var command = FileUploadCommand.Create(givenFormFile, givenMediaDto, givenUserId); var handler = new FileUploadCommandHandler(_fileStorageMock, _contextMock, _mediaIdProviderMock.Object, _timeProviderMock.Object); handler.Handle(command, CancellationToken.None).Wait(); _contextMock.MediaChanges.Should().ContainSingle(mc => mc.Type == MediaChangeType.Create); }
public ActionResult <string> Upload(IFormFile file) { var dto = new FileUploadDto(); dto.Name = file.Name; dto.Content = StreamToBytes(file.OpenReadStream()); dto.Auth = new AuthJwt { IP = this.HttpContext.Connection.RemoteIpAddress.ToString(), Jwt = this.Request.Headers["Authorization"].ToArray()[0], }; this._fileAppService.Upload(dto); throw new NotImplementedException(); }
public async Task <PublicLogoForReturnDto> Create(FileUploadDto uploadDto) { var uploadFile = await upload.Upload(uploadDto.File, "publiclogo"); var mapForCreate = new PublicLogoForCreationDto(); mapForCreate.Name = uploadFile.Name; mapForCreate.FullPath = uploadFile.FullPath; mapForCreate.FileType = uploadFile.FileType; mapForCreate.IsMain = false; var mapForDb = mapper.Map <PublicLogo>(mapForCreate); var createPhoto = await publicLogoDal.Add(mapForDb); return(mapper.Map <PublicLogo, PublicLogoForReturnDto>(createPhoto)); }
public void GivenMediaWithSingleDotAtFileNameEnd_DataTypeIsEmptyString() { var givenFileName = "newFile."; var givenFileContent = "None"; var givenFormFile = FormFileFactory.Create(givenFileName, givenFileContent); var givenTags = new[] { "pigeons", "flying rats" }; var givenMediaDto = new FileUploadDto(givenTags, _givenDate, false); var command = FileUploadCommand.Create(givenFormFile, givenMediaDto, string.Empty); var handler = new FileUploadCommandHandler(_fileStorageMock, _contextMock, _mediaIdProviderMock.Object, _timeProviderMock.Object); handler.Handle(command, CancellationToken.None).Wait(); _contextMock.MediaInstances.Find(_givenMediaInstanceId).DataType.Should().BeEmpty(); }
public void GivenMediaWithEmptyTagCollection_MediaIsCreatedWithoutTags() { var givenFileName = "newFile"; var givenFileContent = "None"; var givenFormFile = FormFileFactory.Create(givenFileName, givenFileContent); var givenTags = new string[] {}; var givenMediaDto = new FileUploadDto(givenTags, _givenDate, false); var command = FileUploadCommand.Create(givenFormFile, givenMediaDto, string.Empty); var handler = new FileUploadCommandHandler(_fileStorageMock, _contextMock, _mediaIdProviderMock.Object, _timeProviderMock.Object); handler.Handle(command, CancellationToken.None).Wait(); _contextMock.MediaInstances.Find(_givenMediaInstanceId).MediaTags.Should().BeEmpty(); }
public void GivenNewMediaIsUploadedSuccessfully_MediaIsCreatedInDatabase() { var givenFileName = "newFile"; var givenFileContent = "None"; var givenFormFile = FormFileFactory.Create(givenFileName, givenFileContent); var givenTags = new[] { "pigeons", "flying rats" }; var givenMediaDto = new FileUploadDto(givenTags, _givenDate, false); var command = FileUploadCommand.Create(givenFormFile, givenMediaDto, string.Empty); var handler = new FileUploadCommandHandler(_fileStorageMock, _contextMock, _mediaIdProviderMock.Object, _timeProviderMock.Object); handler.Handle(command, CancellationToken.None).Wait(); _contextMock.MediaInstances.Find(_givenMediaInstanceId).Should().NotBeNull(); }
public static FileUploadCommand Create(IFormFile?formFile, FileUploadDto mediaDto, string?authorId) { if (formFile == null) { throw new ArgumentNullException(nameof(formFile)); } if (mediaDto == null) { throw new ArgumentNullException(nameof(mediaDto)); } if (mediaDto.Tags == null) { throw new ArgumentNullException(nameof(mediaDto.Tags)); } return(new FileUploadCommand(formFile, mediaDto, authorId)); }
public void GivenMediaWithValidExtension_DataTypeIsEqualToFileExtension() { var givenFileName = "newFile"; var givenExtension = "png"; var givenFileContent = "None"; var givenFormFile = FormFileFactory.Create(givenFileName + "." + givenExtension, givenFileContent); var givenTags = new[] { "pigeons", "flying rats" }; var givenMediaDto = new FileUploadDto(givenTags, _givenDate, false); var command = FileUploadCommand.Create(givenFormFile, givenMediaDto, string.Empty); var handler = new FileUploadCommandHandler(_fileStorageMock, _contextMock, _mediaIdProviderMock.Object, _timeProviderMock.Object); handler.Handle(command, CancellationToken.None).Wait(); _contextMock.MediaInstances.Find(_givenMediaInstanceId).DataType.Should().BeEquivalentTo(givenExtension); }
public void GivenMediaWithNewTag_NewTagIsCreatedInDatabase() { var givenFileName = "newFile"; var givenFileContent = "None"; var formFile = FormFileFactory.Create(givenFileName, givenFileContent); var givenTag = "pigeons"; var givenTags = new[] { givenTag }; var givenMediaDto = new FileUploadDto(givenTags, _givenDate, false); var command = FileUploadCommand.Create(formFile, givenMediaDto, string.Empty); var handler = new FileUploadCommandHandler(_fileStorageMock, _contextMock, _mediaIdProviderMock.Object, _timeProviderMock.Object); handler.Handle(command, CancellationToken.None).Wait(); _contextMock.Tags.Should().ContainSingle(t => t.Name == givenTag); }
public HttpResponseMessage UploadFromUrl(UploadByUrlDto dto) { FileUploadDto result; WebResponse response = null; Stream responseStream = null; var mediaTypeFormatter = new JsonMediaTypeFormatter(); mediaTypeFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain")); try { var request = (HttpWebRequest) WebRequest.Create(dto.Url); request.Credentials = CredentialCache.DefaultCredentials; response = request.GetResponse(); responseStream = response.GetResponseStream(); if (responseStream == null) { throw new Exception("No server response"); } var inMemoryStream = new MemoryStream(); { var count = 0; do { var buffer = new byte[4096]; count = responseStream.Read(buffer, 0, 4096); inMemoryStream.Write(buffer, 0, count); } while (responseStream.CanRead && count > 0); var segments = dto.Url.Split('/'); var fileName = segments[segments.Length - 1]; result = UploadFile(inMemoryStream, PortalSettings, UserInfo, dto.Folder.TextOrEmpty(), dto.Filter.TextOrEmpty(), fileName, dto.Overwrite, dto.IsHostMenu, dto.Unzip); /* Response Content Type cannot be application/json * because IE9 with iframe-transport manages the response * as a file download */ return Request.CreateResponse( HttpStatusCode.OK, result, mediaTypeFormatter, "text/plain"); } } catch (Exception ex) { result = new FileUploadDto { Message = ex.Message }; return Request.CreateResponse( HttpStatusCode.OK, result, mediaTypeFormatter, "text/plain"); } finally { if (response != null) { response.Close(); } if (responseStream != null) { responseStream.Close(); } } }
private static FileUploadDto UploadFile( Stream stream, PortalSettings portalSettings, UserInfo userInfo, string folder, string filter, string fileName, bool overwrite, bool isHostPortal, bool extract) { var result = new FileUploadDto(); BinaryReader reader = null; Stream fileContent = null; try { var extension = Path.GetExtension(fileName).TextOrEmpty().Replace(".", ""); result.FileIconUrl = IconController.GetFileIconUrl(extension); if (!string.IsNullOrEmpty(filter) && !filter.ToLower().Contains(extension.ToLower())) { result.Message = GetLocalizedString("ExtensionNotAllowed"); return result; } if (!IsAllowedExtension(extension)) { result.Message = GetLocalizedString("ExtensionNotAllowed"); return result; } var folderManager = FolderManager.Instance; var effectivePortalId = isHostPortal ? Null.NullInteger : portalSettings.PortalId; // Check if this is a User Folder int userId; var folderInfo = folderManager.GetFolder(effectivePortalId, folder); if (IsUserFolder(folder, out userId)) { var user = UserController.GetUserById(effectivePortalId, userId); if (user != null) { folderInfo = folderManager.GetUserFolder(user); } } if (!PortalSecurity.IsInRoles(userInfo, portalSettings, folderInfo.FolderPermissions.ToString("WRITE")) && !PortalSecurity.IsInRoles(userInfo, portalSettings, folderInfo.FolderPermissions.ToString("ADD"))) { result.Message = GetLocalizedString("NoPermission"); return result; } IFileInfo file; if (!overwrite && FileManager.Instance.FileExists(folderInfo, fileName, true)) { result.Message = GetLocalizedString("AlreadyExists"); result.AlreadyExists = true; file = FileManager.Instance.GetFile(folderInfo, fileName, true); result.FileId = file.FileId; } else { file = FileManager.Instance.AddFile(folderInfo, fileName, stream, true, false, FileManager.Instance.GetContentType(Path.GetExtension(fileName)), userInfo.UserID); if (extract && extension.ToLower() == "zip") { var destinationFolder = FolderManager.Instance.GetFolder(file.FolderId); var invalidFiles = new List<string>(); var filesCount = FileManager.Instance.UnzipFile(file, destinationFolder, invalidFiles); var invalidFilesJson = invalidFiles.Count > 0 ? string.Format("\"{0}\"", string.Join("\",\"", invalidFiles)) : string.Empty; result.Prompt = string.Format("{{\"invalidFiles\":[{0}], \"totalCount\": {1}}}", invalidFilesJson, filesCount); } result.FileId = file.FileId; } fileContent = FileManager.Instance.GetFileContent(file); var path = GetUrl(result.FileId); using (reader = new BinaryReader(fileContent)) { var size = IsImage(fileName) ? ImageHeader.GetDimensions(reader) : new Size(32, 32); result.Orientation = size.Orientation(); } result.Path = result.FileId > 0 ? path : string.Empty; result.FileName = fileName; if (extract && extension.ToLower() == "zip") { FileManager.Instance.DeleteFile(file); } return result; } catch (Exception exe) { Logger.Error(exe.Message); result.Message = exe.Message; return result; } finally { if (reader != null) { reader.Close(); reader.Dispose(); } if (fileContent != null) { fileContent.Close(); fileContent.Dispose(); } } }
public HttpResponseMessage UploadFromUrl(UploadByUrlDto dto) { FileUploadDto result; WebResponse response = null; Stream responseStream = null; var mediaTypeFormatter = new JsonMediaTypeFormatter(); mediaTypeFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain")); if (VerifySafeUrl(dto.Url) == false) { return Request.CreateResponse(HttpStatusCode.BadRequest); } try { var request = (HttpWebRequest) WebRequest.Create(dto.Url); request.Credentials = CredentialCache.DefaultCredentials; response = request.GetResponse(); responseStream = response.GetResponseStream(); if (responseStream == null) { throw new Exception("No server response"); } var fileName = new Uri(dto.Url).Segments.Last(); result = UploadFile(responseStream, PortalSettings, UserInfo, dto.Folder.TextOrEmpty(), dto.Filter.TextOrEmpty(), fileName, dto.Overwrite, dto.IsHostMenu, dto.Unzip); /* Response Content Type cannot be application/json * because IE9 with iframe-transport manages the response * as a file download */ return Request.CreateResponse( HttpStatusCode.OK, result, mediaTypeFormatter, "text/plain"); } catch (Exception ex) { result = new FileUploadDto { Message = ex.Message }; return Request.CreateResponse( HttpStatusCode.OK, result, mediaTypeFormatter, "text/plain"); } finally { if (response != null) { response.Close(); } if (responseStream != null) { responseStream.Close(); } } }