2012-11-08 26 views
0

對於我的生活,我無法找到任何地方如何處理包含多個文件在請求中的多部分/表單數據的任何示例。讓我試着解釋一下。我試圖構建一個WCF服務端點,其中包含一組文本文件中的一組參數,然後是兩個圖像文件,總共包括一篇文章中的三個文件。使用招,我能夠建立請求,它看起來像這樣:WCF多部分/表格數據與多個文件

HEADERS: Content-Type: multipart/form-data; boundary=-------------------------acebdf13572468 
     User-Agent: Fiddler 
     Host: dhiibews.brandonb.com 
     Content-Length: 107865 
REQUESTBODY: ---------------------------acebdf13572468 
      Content-Disposition: form-data; name="Json"; filename="depositcheckrequest.txt" 
      Content-Type: application/json 

      <@INCLUDE *C:\depositcheckrequest.txt*@> 
      ---------------------------acebdf13572468 
      Content-Disposition: form-data; name="frontImage"; filename="front.jpg" 
      Content-Type: image/jpeg 

      <@INCLUDE *C:\front.jpg*@> 
      ---------------------------acebdf13572468 
      Content-Disposition: form-data; name="rearImage"; filename="rear.jpg" 
      Content-Type: image/jpeg 

      <@INCLUDE *C:\rear.jpg*@> 
      ---------------------------acebdf13572468-- 

的包括標籤基本結束了隨地吐痰的文件內容作爲原始數據。

我一直在尋找兩天,我能找到的所有人都可以告訴我如何獲取一個文件的信息,這在我的情況下最終是第一個。我不想只獲得一個文件。正如你可以看到我試圖上傳三個文件。

請幫忙,我如何解析多個文件在一個multipart/form數據POST請求?

+0

我提供的答案結果不起作用,除非所有文件都是文本文件。因爲我想讓它們中的兩個是圖像,所以它們被錯誤地編碼爲字節數組,並且圖像被破壞。 – sanpaco

回答

1

好吧我想出了一個解決方案。事實證明,框架Nancyfx包括一個多部分數據處理器,將您的邊界分隔成子流。所以我偷走了南希源代碼中的相關文件,並將它們複製到我的項目中。相關文件是:

HttpMultipart.cs:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 

namespace MyProjectNamespace 
{ 
    using System.Collections.Generic; 
    using System.IO; 
    using System.Linq; 
    using System.Text; 

    /// <summary> 
    /// Retrieves <see cref="HttpMultipartBoundary"/> instances from a request stream. 
    /// </summary> 
    public class HttpMultipart 
    { 
     private const byte LF = (byte)'\n'; 
     private readonly byte[] boundaryAsBytes; 
     private readonly HttpMultipartBuffer readBuffer; 
     private readonly MemoryStream requestStream; 
     private readonly byte[] closingBoundaryAsBytes; 

     /// <summary> 
     /// Initializes a new instance of the <see cref="HttpMultipart"/> class. 
     /// </summary> 
     /// <param name="requestStream">The request stream to parse.</param> 
     /// <param name="boundary">The boundary marker to look for.</param> 
     public HttpMultipart(Stream requestStream, string boundary) 
     { 
      this.requestStream = new MemoryStream(ToByteArray(requestStream)); 
      this.boundaryAsBytes = GetBoundaryAsBytes(boundary, false); 
      this.closingBoundaryAsBytes = GetBoundaryAsBytes(boundary, true); 
      this.readBuffer = new HttpMultipartBuffer(this.boundaryAsBytes, this.closingBoundaryAsBytes); 
     } 

     /// <summary> 
     /// Gets the <see cref="HttpMultipartBoundary"/> instances from the request stream. 
     /// </summary> 
     /// <returns>An <see cref="IEnumerable{T}"/> instance, containing the found <see cref="HttpMultipartBoundary"/> instances.</returns> 
     public IEnumerable<HttpMultipartBoundary> GetBoundaries() 
     { 
      return 
       (from boundaryStream in this.GetBoundarySubStreams() 
       select new HttpMultipartBoundary(boundaryStream)).ToList(); 
     } 

     private static byte[] GetBoundaryAsBytes(string boundary, bool closing) 
     { 
      var boundaryBuilder = new StringBuilder(); 

      boundaryBuilder.Append("--"); 
      boundaryBuilder.Append(boundary); 

      if (closing) 
      { 
       boundaryBuilder.Append("--"); 
      } 
      else 
      { 
       boundaryBuilder.Append('\r'); 
       boundaryBuilder.Append('\n'); 
      } 

      var bytes = 
       Encoding.ASCII.GetBytes(boundaryBuilder.ToString()); 

      return bytes; 
     } 

     private IEnumerable<HttpMultipartSubStream> GetBoundarySubStreams() 
     { 
      var boundarySubStreams = new List<HttpMultipartSubStream>(); 
      var boundaryStart = this.GetNextBoundaryPosition(); 

      while (MultipartIsNotCompleted(boundaryStart)) 
      { 
       var boundaryEnd = this.GetNextBoundaryPosition(); 
       boundarySubStreams.Add(new HttpMultipartSubStream(
        this.requestStream, 
        boundaryStart, 
        this.GetActualEndOfBoundary(boundaryEnd))); 

       boundaryStart = boundaryEnd; 
      } 

      return boundarySubStreams; 
     } 

     private bool MultipartIsNotCompleted(long boundaryPosition) 
     { 
      return boundaryPosition > -1 && !this.readBuffer.IsClosingBoundary; 
     } 

     //we add two because or the \r\n before the boundary 
     private long GetActualEndOfBoundary(long boundaryEnd) 
     { 
      if (this.CheckIfFoundEndOfStream()) 
      { 
       return this.requestStream.Position - (this.readBuffer.Length + 2); 
      } 
      return boundaryEnd - (this.readBuffer.Length + 2); 
     } 

     private bool CheckIfFoundEndOfStream() 
     { 
      return this.requestStream.Position.Equals(this.requestStream.Length); 
     } 

     private long GetNextBoundaryPosition() 
     { 
      this.readBuffer.Reset(); 
      while (true) 
      { 
       var byteReadFromStream = this.requestStream.ReadByte(); 

       if (byteReadFromStream == -1) 
       { 
        return -1; 
       } 

       this.readBuffer.Insert((byte)byteReadFromStream); 

       if (this.readBuffer.IsFull && (this.readBuffer.IsBoundary || this.readBuffer.IsClosingBoundary)) 
       { 
        return this.requestStream.Position; 
       } 

       if (byteReadFromStream.Equals(LF) || this.readBuffer.IsFull) 
       { 
        this.readBuffer.Reset(); 
       } 
      } 
     } 

     private byte[] ToByteArray(Stream stream) 
     { 
      byte[] buffer = new byte[32768]; 
      using (MemoryStream ms = new MemoryStream()) 
      { 
       while (true) 
       { 
        int read = stream.Read(buffer, 0, buffer.Length); 
        if (read <= 0) 
        { 
         return ms.ToArray(); 
        } 
        ms.Write(buffer, 0, read); 
       } 
      } 
     } 
    } 
} 

HttpMultipartBuffer.cs:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 

namespace MyProjectNamespace 
{ 
    public class HttpMultipartBuffer 
    { 
     private readonly byte[] boundaryAsBytes; 
     private readonly byte[] closingBoundaryAsBytes; 
     private readonly byte[] buffer; 
     private int position; 

     /// <summary> 
     /// Initializes a new instance of the <see cref="HttpMultipartBuffer"/> class. 
     /// </summary> 
     /// <param name="boundaryAsBytes">The boundary as a byte-array.</param> 
     /// <param name="closingBoundaryAsBytes">The closing boundary as byte-array</param> 
     public HttpMultipartBuffer(byte[] boundaryAsBytes, byte[] closingBoundaryAsBytes) 
     { 
      this.boundaryAsBytes = boundaryAsBytes; 
      this.closingBoundaryAsBytes = closingBoundaryAsBytes; 
      this.buffer = new byte[this.boundaryAsBytes.Length]; 
     } 

     /// <summary> 
     /// Gets a value indicating whether the buffer contains the same values as the boundary. 
     /// </summary> 
     /// <value><see langword="true"/> if buffer contains the same values as the boundary; otherwise, <see langword="false"/>.</value> 
     public bool IsBoundary 
     { 
      get { return this.buffer.SequenceEqual(this.boundaryAsBytes); } 
     } 

     public bool IsClosingBoundary 
     { 
      get { return this.buffer.SequenceEqual(this.closingBoundaryAsBytes); } 
     } 

     /// <summary> 
     /// Gets a value indicating whether this buffer is full. 
     /// </summary> 
     /// <value><see langword="true"/> if buffer is full; otherwise, <see langword="false"/>.</value> 
     public bool IsFull 
     { 
      get { return this.position.Equals(this.buffer.Length); } 
     } 

     /// <summary> 
     /// Gets the the number of bytes that can be stored in the buffer. 
     /// </summary> 
     /// <value>The number of butes that can be stored in the buffer.</value> 
     public int Length 
     { 
      get { return this.buffer.Length; } 
     } 

     /// <summary> 
     /// Resets the buffer so that inserts happens from the start again. 
     /// </summary> 
     /// <remarks>This does not clear any previously written data, just resets the buffer position to the start. Data that is inserted after Reset has been called will overwrite old data.</remarks> 
     public void Reset() 
     { 
      this.position = 0; 
     } 

     /// <summary> 
     /// Inserts the specified value into the buffer and advances the internal position. 
     /// </summary> 
     /// <param name="value">The value to insert into the buffer.</param> 
     /// <remarks>This will throw an <see cref="ArgumentOutOfRangeException"/> is you attempt to call insert more times then the <see cref="Length"/> of the buffer and <see cref="Reset"/> was not invoked.</remarks> 
     public void Insert(byte value) 
     { 
      this.buffer[this.position++] = value; 
     } 
    } 
} 

HttpMultipartBoundary.cs:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Text.RegularExpressions; 
using System.Web; 

namespace DHIWebSvc.Models 
{ 
    public class HttpMultipartBoundary 
    { 
     private const byte LF = (byte)'\n'; 
     private const byte CR = (byte)'\r'; 

     /// <summary> 
     /// Initializes a new instance of the <see cref="HttpMultipartBoundary"/> class. 
     /// </summary> 
     /// <param name="boundaryStream">The stream that contains the boundary information.</param> 
     public HttpMultipartBoundary(HttpMultipartSubStream boundaryStream) 
     { 
      this.Value = boundaryStream; 
      this.ExtractHeaders(); 
     } 

     /// <summary> 
     /// Gets the contents type of the boundary value. 
     /// </summary> 
     /// <value>A <see cref="string"/> containing the name of the value if it is available; otherwise <see cref="string.Empty"/>.</value> 
     public string ContentType { get; private set; } 

     /// <summary> 
     /// Gets or the filename for the boundary value. 
     /// </summary> 
     /// <value>A <see cref="string"/> containing the filename value if it is available; otherwise <see cref="string.Empty"/>.</value> 
     /// <remarks>This is the RFC2047 decoded value of the filename attribute of the Content-Disposition header.</remarks> 
     public string Filename { get; private set; } 

     /// <summary> 
     /// Gets name of the boundary value. 
     /// </summary> 
     /// <remarks>This is the RFC2047 decoded value of the name attribute of the Content-Disposition header.</remarks> 
     public string Name { get; private set; } 

     /// <summary> 
     /// A stream containig the value of the boundary. 
     /// </summary> 
     /// <remarks>This is the RFC2047 decoded value of the Content-Type header.</remarks> 
     public HttpMultipartSubStream Value { get; private set; } 

     private void ExtractHeaders() 
     { 
      while (true) 
      { 
       var header = 
        this.ReadLineFromStream(); 

       if (string.IsNullOrEmpty(header)) 
       { 
        break; 
       } 

       if (header.StartsWith("Content-Disposition", StringComparison.CurrentCultureIgnoreCase)) 
       { 
        this.Name = Regex.Match(header, @"name=""(?<name>[^\""]*)", RegexOptions.IgnoreCase).Groups["name"].Value; 
        this.Filename = Regex.Match(header, @"filename=""(?<filename>[^\""]*)", RegexOptions.IgnoreCase).Groups["filename"].Value; 
       } 

       if (header.StartsWith("Content-Type", StringComparison.InvariantCultureIgnoreCase)) 
       { 
        this.ContentType = header.Split(new[] { ' ' }).Last().Trim(); 
       } 
      } 

      this.Value.PositionStartAtCurrentLocation(); 
     } 

     private string ReadLineFromStream() 
     { 
      var readBuffer = new StringBuilder(); 

      while (true) 
      { 
       var byteReadFromStream = this.Value.ReadByte(); 

       if (byteReadFromStream == -1) 
       { 
        return null; 
       } 

       if (byteReadFromStream.Equals(LF)) 
       { 
        break; 
       } 

       readBuffer.Append((char)byteReadFromStream); 
      } 

      var lineReadFromStream = 
       readBuffer.ToString().Trim(new[] { (char)CR }); 

      return lineReadFromStream; 
     } 
    } 
} 

終於...

HttpMultipartSubStream.cs:

using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Linq; 
using System.Web; 

namespace DHIWebSvc.Models 
{ 
    public class HttpMultipartSubStream : Stream 
    { 
     private readonly Stream stream; 
     private readonly long end; 
     private long start; 
     private long position; 

     /// <summary> 
     /// Initializes a new instance of the <see cref="HttpMultipartSubStream"/> class. 
     /// </summary> 
     /// <param name="stream">The stream to create the sub-stream ontop of.</param> 
     /// <param name="start">The start offset on the parent stream where the sub-stream should begin.</param> 
     /// <param name="end">The end offset on the parent stream where the sub-stream should end.</param> 
     public HttpMultipartSubStream(Stream stream, long start, long end) 
     { 
      this.stream = stream; 
      this.start = start; 
      this.position = start; 
      this.end = end; 
     } 

     /// <summary> 
     /// When overridden in a derived class, gets a value indicating whether the current stream supports reading. 
     /// </summary> 
     /// <returns><see langword="true"/> if the stream supports reading; otherwise, <see langword="false"/>.</returns> 
     public override bool CanRead 
     { 
      get { return true; } 
     } 

     /// <summary> 
     /// When overridden in a derived class, gets a value indicating whether the current stream supports seeking. 
     /// </summary> 
     /// <returns><see langword="true"/> if the stream supports seeking; otherwise, <see langword="false"/>.</returns> 
     public override bool CanSeek 
     { 
      get { return true; } 
     } 

     /// <summary> 
     /// When overridden in a derived class, gets a value indicating whether the current stream supports writing. 
     /// </summary> 
     /// <returns><see langword="true"/> if the stream supports writing; otherwise, <see langword="false"/>.</returns> 
     public override bool CanWrite 
     { 
      get { return false; } 
     } 

     /// <summary> 
     /// When overridden in a derived class, gets the length in bytes of the stream. 
     /// </summary> 
     /// <returns>A long value representing the length of the stream in bytes.</returns> 
     /// <exception cref="NotSupportedException">A class derived from Stream does not support seeking. </exception><exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed.</exception> 
     public override long Length 
     { 
      get 
      { 
       return this.end - this.start; 
      } 
     } 

     /// <summary> 
     /// When overridden in a derived class, gets or sets the position within the current stream. 
     /// </summary> 
     /// <returns> 
     /// The current position within the stream. 
     /// </returns> 
     /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception><exception cref="T:System.NotSupportedException">The stream does not support seeking. </exception><exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception><filterpriority>1</filterpriority> 
     public override long Position 
     { 
      get { return this.position - this.start; } 
      set { this.position = this.Seek(value, SeekOrigin.Begin); } 
     } 

     public void PositionStartAtCurrentLocation() 
     { 
      this.start = this.stream.Position; 
     } 

     /// <summary> 
     /// When overridden in a derived class, clears all buffers for this stream and causes any buffered data to be written to the underlying device. 
     /// </summary> 
     /// <remarks>In the <see cref="HttpMultipartSubStream"/> type this method is implemented as no-op.</remarks> 
     public override void Flush() 
     { 
     } 

     /// <summary> 
     /// When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read. 
     /// </summary> 
     /// <returns>The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached. </returns> 
     /// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between <paramref name="offset"/> and (<paramref name="offset"/> + <paramref name="count"/> - 1) replaced by the bytes read from the current source. </param> 
     /// <param name="offset">The zero-based byte offset in <paramref name="buffer"/> at which to begin storing the data read from the current stream.</param> 
     /// <param name="count">The maximum number of bytes to be read from the current stream. </param> 
     public override int Read(byte[] buffer, int offset, int count) 
     { 
      if (count > (this.end - this.position)) 
      { 
       count = (int)(this.end - this.position); 
      } 

      if (count <= 0) 
      { 
       return 0; 
      } 

      this.stream.Position = this.position; 

      var bytesReadFromStream = 
       this.stream.Read(buffer, offset, count); 

      this.RepositionAfterRead(bytesReadFromStream); 

      return bytesReadFromStream; 
     } 

     /// <summary> 
     /// Reads a byte from the stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream. 
     /// </summary> 
     /// <returns>The unsigned byte cast to an Int32, or -1 if at the end of the stream.</returns> 
     public override int ReadByte() 
     { 
      if (this.position >= this.end) 
      { 
       return -1; 
      } 

      this.stream.Position = this.position; 

      var byteReadFromStream = this.stream.ReadByte(); 

      this.RepositionAfterRead(1); 

      return byteReadFromStream; 
     } 

     /// <summary> 
     /// When overridden in a derived class, sets the position within the current stream. 
     /// </summary> 
     /// <returns>The new position within the current stream.</returns> 
     /// <param name="offset">A byte offset relative to the <paramref name="origin"/> parameter.</param> 
     /// <param name="origin">A value of type <see cref="SeekOrigin"/> indicating the reference point used to obtain the new position.</param> 
     public override long Seek(long offset, SeekOrigin origin) 
     { 
      var subStreamRelativePosition = 
       this.CalculateSubStreamRelativePosition(origin, offset); 

      this.ThrowExceptionIsPositionIsOutOfBounds(subStreamRelativePosition); 

      this.position = this.stream.Seek(subStreamRelativePosition, SeekOrigin.Begin); 

      return this.position; 
     } 

     /// <summary> 
     /// When overridden in a derived class, sets the length of the current stream. 
     /// </summary> 
     /// <param name="value">The desired length of the current stream in bytes.</param> 
     /// <remarks>This will always throw a <see cref="InvalidOperationException"/> for the <see cref="HttpMultipartSubStream"/> type.</remarks> 
     public override void SetLength(long value) 
     { 
      throw new InvalidOperationException(); 
     } 

     /// <summary> 
     /// When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. 
     /// </summary> 
     /// <param name="buffer">An array of bytes. This method copies <paramref name="count"/> bytes from <paramref name="buffer"/> to the current stream. </param> 
     /// <param name="offset">The zero-based byte offset in <paramref name="buffer"/> at which to begin copying bytes to the current stream. </param> 
     /// <param name="count">The number of bytes to be written to the current stream. </param> 
     /// <remarks>This will always throw a <see cref="InvalidOperationException"/> for the <see cref="HttpMultipartSubStream"/> type.</remarks> 
     public override void Write(byte[] buffer, int offset, int count) 
     { 
      throw new InvalidOperationException(); 
     } 

     private void ThrowExceptionIsPositionIsOutOfBounds(long subStreamRelativePosition) 
     { 
      if (subStreamRelativePosition < 0 || subStreamRelativePosition > this.end) 
      { 
       throw new InvalidOperationException(); 
      } 
     } 

     private long CalculateSubStreamRelativePosition(SeekOrigin origin, long offset) 
     { 
      var subStreamRelativePosition = 0L; 

      switch (origin) 
      { 
       case SeekOrigin.Begin: 
        subStreamRelativePosition = this.start + offset; 
        break; 

       case SeekOrigin.Current: 
        subStreamRelativePosition = this.position + offset; 
        break; 

       case SeekOrigin.End: 
        subStreamRelativePosition = this.end + offset; 
        break; 
      } 
      return subStreamRelativePosition; 
     } 

     private void RepositionAfterRead(int bytesReadFromStream) 
     { 
      if (bytesReadFromStream == -1) 
      { 
       this.position = this.end; 
      } 
      else 
      { 
       this.position += bytesReadFromStream; 
      } 
     } 
    } 
} 

的用途是什麼,我試圖做的比較簡單。我只是定義了一個邊界,只查找特定的部分名稱。因此,對於我的問題中的示例,我使用了帶有三個文件的邊界"-------------------------acebdf13572468"Json,frontImagerearImage

相關問題