Exemplo n.º 1
0
        public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)
        {
            if (parent == null)
            {
                throw Error.ArgumentNull("parent");
            }

            if (headers == null)
            {
                throw Error.ArgumentNull("headers");
            }

            string localFilePath;

            try
            {
                string filename = GetLocalFileName(headers);
                localFilePath = Path.Combine(_rootPath, Path.GetFileName(filename));
            }
            catch (Exception e)
            {
                throw Error.InvalidOperation(e, Properties.Resources.MultipartStreamProviderInvalidLocalFileName);
            }

            // Add local file name
            MultipartFileData fileData = new MultipartFileData(headers, localFilePath);

            _fileData.Add(fileData);

            return(File.Create(localFilePath, _bufferSize, FileOptions.Asynchronous));
        }
Exemplo n.º 2
0
        public void Constructor_InitializesCorrectly()
        {
            // Arrange
            HttpContentHeaders headers  = FormattingUtilities.CreateEmptyContentHeaders();
            string             fileName = "filename";

            // Act
            MultipartFileData fileData = new MultipartFileData(headers, fileName);

            Assert.Same(headers, fileData.Headers);
            Assert.Same(fileName, fileData.LocalFileName);
        }
        private static string GetBlobName(MultipartFileData fileData)
        {
            string blobName = null;
            ContentDispositionHeaderValue contentDisposition = fileData.Headers.ContentDisposition;
            if (contentDisposition != null)
            {
                try
                {
                    blobName = Path.GetFileName(contentDisposition.FileName.Trim('"'));
                }
                catch
                { }
            }

            return blobName ?? Path.GetFileName(fileData.LocalFileName);
        }
		private StringContent CloneHeaderContent(string path, MultipartFileData origin)
		{
			var content = new StringContent(path);

			ContentDispositionHeaderValue disposition;
			ContentDispositionHeaderValue.TryParse(origin.Headers.ContentDisposition.ToString(), out disposition);

			content.Headers.ContentDisposition = disposition;

			content.Headers.ContentDisposition.Name = origin.Headers.ContentDisposition.Name.ToUnquoted();
			content.Headers.ContentDisposition.FileName = Path.GetFileName(path);

			content.Headers.ContentType.MediaType = MimeTypes.MapNameToMimeType(path);

			return content;
		}
	    private string FileName(MultipartFileData fileData)
	    {
			var fileName = string.Empty;

			fileName = fileData.Headers.ContentDisposition.FileName;
			if (fileName.StartsWith("\"") && fileName.EndsWith("\""))
			{
				fileName = fileName.Trim('"');
			}
			if (fileName.Contains(@"/") || fileName.Contains(@"\"))
			{
				fileName = Path.GetFileName(fileName);
			}

		    return fileName;
	    }
Exemplo n.º 6
0
        /// <summary>
        /// Gets the stream instance to which the message body part is written.
        /// </summary>
        /// <param name="parent">The HTTP content that contains this body part.</param>
        /// <param name="headers">Header fields describing the body part.</param>
        /// <returns>The <see cref="Stream"/> instance where the message body part is written.</returns>
        public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)
        {
            if (headers == null)
            {
                throw new ArgumentNullException("headers");
            }

            var filename = GetLocalFileName(headers);
            var fullpath = Path.Combine(RootPath, filename);

            var data = new MultipartFileData(headers, fullpath);

            FileData.Add(data);

            var stream_wrapper = FileWrapper.Create(fullpath, BufferSize, FileOptions.Asynchronous);

            return(stream_wrapper.StreamInstance);
        }
Exemplo n.º 7
0
 private void MoveFileToDraft(MultipartFileData file)
 {
     string root = HttpContext.Current.Server.MapPath("~/App_Data/draft");
     string fileName = string.Format("{0}\\{1}.{2}", root, GetFileName(file.Headers.ContentDisposition.FileName), "xml");
     Trace.WriteLine("draft: " + fileName);
     if(File.Exists(fileName))
     {
         File.Delete(fileName);
     }
     try
     {
         File.Move(file.LocalFileName, fileName);
         Console.WriteLine("Moved"); // Success
     }
     catch (IOException ex)
     {
         Console.WriteLine(ex.Message); // Write error
     }
 }
Exemplo n.º 8
0
        public void GetStream()
        {
            Stream stream0 = null;
            Stream stream1 = null;

            try
            {
                string tempPath = Path.GetTempPath();
                MultipartFormDataContent content = new MultipartFormDataContent();
                content.Add(new StringContent("Content 1"), "NoFile");
                content.Add(new StringContent("Content 2"), "File", "Filename");

                MultipartFormDataStreamProvider provider = new MultipartFormDataStreamProvider(
                    tempPath
                    );
                stream0 = provider.GetStream(content, content.ElementAt(0).Headers);
                stream1 = provider.GetStream(content, content.ElementAt(1).Headers);

                Assert.IsType <MemoryStream>(stream0);
                Assert.IsType <FileStream>(stream1);

                MultipartFileData fileData        = Assert.Single(provider.FileData);
                string            partialFileName = String.Format("{0}BodyPart_", tempPath);
                Assert.Contains(partialFileName, fileData.LocalFileName);

                Assert.Same(
                    content.ElementAt(1).Headers.ContentDisposition,
                    fileData.Headers.ContentDisposition
                    );
            }
            finally
            {
                if (stream0 != null)
                {
                    stream0.Close();
                }

                if (stream1 != null)
                {
                    stream1.Close();
                }
            }
        }
        public static string localSaveFile(MultipartFileData file)
        {
            string fileName = file.Headers.ContentDisposition.FileName;
            if (fileName.StartsWith("\"") && fileName.EndsWith("\""))
            {
                fileName = fileName.Trim('"');
            }
            if (fileName.Contains(@"/") || fileName.Contains(@"\"))
            {
                fileName = Path.GetFileName(fileName);
            }

            //檔名加上時間戳記

            fileName = String.Format("{0}_{1}", Convert.ToInt32(DateTime.UtcNow.AddHours(8).Subtract(new DateTime(1970, 1, 1)).TotalSeconds), fileName);

            string newPath = Path.Combine(ConfigurationManager.AppSettings["ImageLocalPath"], fileName);

            // Ensure that the target does not exist.
            if (File.Exists(newPath))
                File.Delete(newPath);

            File.Move(file.LocalFileName, newPath);

            if (File.Exists(file.LocalFileName))
                File.Delete(file.LocalFileName);

            //fileName = String.Format("/Content/uploads/{1}", ServerUploadFolder, fileName);

            return fileName;
        }
        public static string blobSaveFile(MultipartFileData file)
        {
            string fileName = file.Headers.ContentDisposition.FileName;
            if (fileName.StartsWith("\"") && fileName.EndsWith("\""))
            {
                fileName = fileName.Trim('"');
            }
            if (fileName.Contains(@"/") || fileName.Contains(@"\"))
            {
                fileName = Path.GetFileName(fileName);
            }

            //檔名加上時間戳記

            fileName = String.Format("{0}_{1}", Convert.ToInt32(DateTime.UtcNow.AddHours(8).Subtract(new DateTime(1970, 1, 1)).TotalSeconds), fileName);

            // Retrieve reference to a blob named "myblob".
            CloudBlockBlob blockBlob = ImageContainer.GetBlockBlobReference(fileName);

            // Create or overwrite the "myblob" blob with contents from a local file.
            using (var fileStream = System.IO.File.OpenRead(file.LocalFileName))
            {
                blockBlob.UploadFromStream(fileStream);
            }
            if (File.Exists(file.LocalFileName))
                File.Delete(file.LocalFileName);


            return fileName;
        }
Exemplo n.º 11
0
        private async Task<MediaFile> SaveImage(MultipartFileData file)
        {
            var path = file.LocalFileName;
            var fileStream = new FileStream(path, FileMode.Open);

            using (var content = new MultipartContent())
            {
                content.Add(new StreamContent(fileStream));

                var upload = new MediaUpload
                {
                    Content = content,
                    ContentSize = fileStream.Length,
                    ContentType = "image/jpeg"
                };

                var picture = await _mediaService.UploadMediaAsync(upload);
                return picture;
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// get the deserialized file name (oringinal file name) from the upload file data
        /// </summary>
        /// <param name="fileData"></param>
        /// <returns></returns>
        private string GetDeserializedFileName(MultipartFileData fileData)
        {
            var fileName = fileData.Headers.ContentDisposition.FileName;
            // IE fix
            // when using IE to upload file, the ContentDisposition.FileName contains the full local path of the file
            if (fileName.Contains("\\"))
            {
                // remove the path and only keep the file name in json format
                var lastIndexOfPathCharacter = fileName.LastIndexOf("\\");
                fileName = "\"" + fileName.Substring(lastIndexOfPathCharacter + 1); // json format
            }

            return JsonConvert.DeserializeObject(fileName).ToString();
        }
Exemplo n.º 13
0
 private string GetDeserializedFileName(MultipartFileData fileData)
 {
     var fileName = GetFileName(fileData);
     return JsonConvert.DeserializeObject(fileName).ToString();
 }
        public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)
        {
            if (parent == null)
            {
                throw Error.ArgumentNull("parent");
            }

            if (headers == null)
            {
                throw Error.ArgumentNull("headers");
            }

            string localFilePath;
            try
            {
                string filename = GetLocalFileName(headers);
                localFilePath = Path.Combine(_rootPath, Path.GetFileName(filename));
            }
            catch (Exception e)
            {
                throw Error.InvalidOperation(e, Properties.Resources.MultipartStreamProviderInvalidLocalFileName);
            }

            // Add local file name 
            MultipartFileData fileData = new MultipartFileData(headers, localFilePath);
            _fileData.Add(fileData);

            return File.Create(localFilePath, _bufferSize, FileOptions.Asynchronous);
        }
Exemplo n.º 15
0
        private void RenameChunk(MultipartFileData chunk, int chunkNumber, string identifier)
        {
            string generatedFileName = chunk.LocalFileName;
            string chunkFileName = GetChunkFileName(chunkNumber, identifier);
            if (File.Exists(chunkFileName)) File.Delete(chunkFileName);
            File.Move(generatedFileName, chunkFileName);

        }
Exemplo n.º 16
0
 public string GetFileName(MultipartFileData fileData)
 {
     return fileData.Headers.ContentDisposition.FileName;
 }
 /// <summary>
 /// Tries to extract the name of the blob out of the content disposition.
 /// </summary>
 /// <param name="fileData">A single element of the multipart form-data.</param>
 /// <returns>The file name or <c>null</c> if none was retrieved.</returns>
 private static string GetBlobName(MultipartFileData fileData)
 {
     string blobName = null;
     var contentDisposition = fileData.Headers.ContentDisposition;
     if (contentDisposition == null)
     {
         return Path.GetFileName(fileData.LocalFileName);
     }
     try
     {
         blobName = Path.GetFileName(contentDisposition.FileName.Trim('"'));
     }
     catch (Exception ex)
     {
         TraceUtil.WriteTraceError(ex.Message);
     }
     return blobName ?? Path.GetFileName(fileData.LocalFileName);
 }
Exemplo n.º 18
0
 public void ProcessNewXml(MultipartFileData file)
 {
     Trace.WriteLine("Server file path: " + file.LocalFileName);
     MoveFileToDraft(file);
 }
Exemplo n.º 19
0
 private static void MoveTempFileToTarget(MultipartFileData multipartFileData, string destFileName)
 {
     File.Copy(multipartFileData.LocalFileName, destFileName);
     File.Delete(multipartFileData.LocalFileName);
 }
Exemplo n.º 20
0
        private async Task<FileUploadModel> UploadOneToBlob(CloudBlobContainer blobContainer, MultipartFileData fileData, IEnumerable<string> supportedFileTypes = null)
        {
            var fileName = Path.GetFileName(fileData.Headers.ContentDisposition.FileName.Trim('"'));

            if (supportedFileTypes != null)
                FileUtility.VerifyFileExtensionSupported(fileName, supportedFileTypes);

            var blob = blobContainer.GetBlockBlobReference(fileName);

            blob.Properties.ContentType = fileData.Headers.ContentType.MediaType;

            using (var fs = File.OpenRead(fileData.LocalFileName))
            {
                await blob.UploadFromStreamAsync(fs);
            }

            File.Delete(fileData.LocalFileName);

            var fileUpload = new FileUploadModel
            {
                FileName = blob.Name,
                FileUrl = blob.Uri.AbsoluteUri,
                FileSizeInBytes = blob.Properties.Length
            };
            return fileUpload;
        }
Exemplo n.º 21
-1
        public void Constructor_InitializesCorrectly()
        {
            // Arrange
            HttpContentHeaders headers = FormattingUtilities.CreateEmptyContentHeaders();
            string fileName = "filename";

            // Act
            MultipartFileData fileData = new MultipartFileData(headers, fileName);


            Assert.Same(headers, fileData.Headers);
            Assert.Same(fileName, fileData.LocalFileName);
        }