如何使用Webclient在文件上传表单 - 数据请求中发送params?

时间:2017-07-14 01:39:58

标签: c# asp.net-web-api webclient

我想在其他较低级别的http库中使用Webclient(我从控制台应用程序中使用它)。我想发送一个像下面的http请求(这是来自fidler,但你明白了):

部首:

Content-Type: multipart/form-data; boundary=-------------------------acebdf13572468
User-Agent: Fiddler
Host: localhost:54650
Content-Length: 134682

体:

---------------------------acebdf13572468
Content-Disposition: form-data; name="model" 

ThisIsACustomParam
---------------------------acebdf13572468
Content-Disposition: form-data; name="fieldNameHere"; filename="12356566_919196481467578_946278252_n.jpg"
Content-Type: image/jpeg

<@INCLUDE *C:\MyLocalFolder\12356566_919196481467578_946278252_n.jpg*@>
---------------------------acebdf13572468--

我深入挖掘了webclient类,在反编译之后,我发现了很多我想要的东西。我想知道我是否必须更换WebClient(我希望不会)

WebClient反编译的UploadFile方法:

public byte[] UploadFile(Uri address, string method, string fileName)
{
  if (Logging.On)
    Logging.Enter(Logging.Web, (object) this, "UploadFile", address.ToString() + ", " + method);
  if (address == (Uri) null)
    throw new ArgumentNullException("address");
  if (fileName == null)
    throw new ArgumentNullException("fileName");
  if (method == null)
    method = this.MapToDefaultMethod(address);
  FileStream fs = (FileStream) null;
  WebRequest request = (WebRequest) null;
  this.ClearWebClientState();
  try
  {
    this.m_Method = method;
    byte[] formHeaderBytes = (byte[]) null;
    byte[] boundaryBytes = (byte[]) null;
    byte[] buffer = (byte[]) null;
    Uri uri = this.GetUri(address);
    this.OpenFileInternal(uri.Scheme != Uri.UriSchemeFile, fileName, ref fs, ref buffer, ref formHeaderBytes, ref boundaryBytes);
    request = this.m_WebRequest = this.GetWebRequest(uri);
    this.UploadBits(request, (Stream) fs, buffer, 0, formHeaderBytes, boundaryBytes, (CompletionDelegate) null, (CompletionDelegate) null, (AsyncOperation) null);
    byte[] numArray = this.DownloadBits(request, (Stream) null, (CompletionDelegate) null, (AsyncOperation) null);
    if (Logging.On)
      Logging.Exit(Logging.Web, (object) this, "UploadFile", (object) numArray);
    return numArray;
  }
  catch (Exception ex)
  {
    Exception innerException = ex;
    if (fs != null)
      fs.Close();
    if (innerException is ThreadAbortException || innerException is StackOverflowException || innerException is OutOfMemoryException)
    {
      throw;
    }
    else
    {
      if (!(innerException is WebException) && !(innerException is SecurityException))
        innerException = (Exception) new WebException(SR.GetString("net_webclient"), innerException);
      WebClient.AbortRequest(request);
      throw innerException;
    }
  }
  finally
  {
    this.CompleteWebClientState();
  }
}

0 个答案:

没有答案