none
HttpWebRequest上传图片的问题

全部回复

  • 参考这里

    http://stackoverflow.com/questions/566462/upload-files-with-httpwebrequest-multipart-form-data

    public static string UploadFilesToRemoteUrl(string url, string[] files, NameValueCollection formFields = null)
    {
       
    string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");

       
    HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
        request
    .ContentType = "multipart/form-data; boundary=" +
                                boundary
    ;
        request
    .Method = "POST";
        request
    .KeepAlive = true;

       
    Stream memStream = new System.IO.MemoryStream();

       
    var boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" +
                                                                boundary
    + "\r\n");
       
    var endBoundaryBytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" +
                                                                    boundary
    + "--");


       
    string formdataTemplate = "\r\n--" + boundary +
                                   
    "\r\nContent-Dis-data; name=\"{0}\";\r\n\r\n{1}";

       
    if (formFields != null)
       
    {
           
    foreach (string key in formFields.Keys)
           
    {
               
    string formitem = string.Format(formdataTemplate, key, formFields[key]);
               
    byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
                memStream
    .Write(formitembytes, 0, formitembytes.Length);
           
    }
       
    }

       
    string headerTemplate =
           
    "Content-Dis-data; name=\"{0}\"; filename=\"{1}\"\r\n" +
           
    "Content-Type: application/octet-stream\r\n\r\n";

       
    for (int i = 0; i < files.Length; i++)
       
    {
            memStream
    .Write(boundarybytes, 0, boundarybytes.Length);
           
    var header = string.Format(headerTemplate, "uplTheFile", files[i]);
           
    var headerbytes = System.Text.Encoding.UTF8.GetBytes(header);

            memStream
    .Write(headerbytes, 0, headerbytes.Length);

           
    using (var fileStream = new FileStream(files[i], FileMode.Open, FileAccess.Read))
           
    {
               
    var buffer = new byte[1024];
               
    var bytesRead = 0;
               
    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
               
    {
                    memStream
    .Write(buffer, 0, bytesRead);
               
    }
           
    }
       
    }

        memStream
    .Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
        request
    .ContentLength = memStream.Length;

       
    using (Stream requestStream = request.GetRequestStream())
       
    {
            memStream
    .Position = 0;
           
    byte[] tempBuffer = new byte[memStream.Length];
            memStream
    .Read(tempBuffer, 0, tempBuffer.Length);
            memStream
    .Close();
            requestStream
    .Write(tempBuffer, 0, tempBuffer.Length);
       
    }

       
    using (var response = request.GetResponse())
       
    {
           
    Stream stream2 = response.GetResponseStream();
           
    StreamReader reader2 = new StreamReader(stream2);
           
    return reader2.ReadToEnd();
       
    }
    }


    专注于.NET ERP/CRM开发框架,C/S架构,SQL Server + ORM(LLBL Gen Pro) + Infragistics WinForms

    2016年9月8日 5:51
  • 中文版带注释

    http://www.cnblogs.com/loujady/archive/2011/09/13/2174695.html


    专注于.NET ERP/CRM开发框架,C/S架构,SQL Server + ORM(LLBL Gen Pro) + Infragistics WinForms


    2016年9月8日 5:52
  • 你好,

    你也可以参考以下代码:

    #取参数:

    private string GetPostData() 
    { 
        string boundary = "--" + this._Boundary; 
        int arrReqs = this._ParamsCollection.Count * 5; 
        string[] auxReqBody = new string[arrReqs]; 
        int count = 0; 
        foreach(ParamsStruct par in this._ParamsCollection) 
        { 
            auxReqBody[count] = boundary; 
            count++; 
            switch (par.Type) 
            { 
                case ParamsStruct.ParamType.File: 
                { 
                    auxReqBody[count] = "Content-Dis; name=\"" + 
                       par.Name + "\"; filename=\"" + par.GetOnlyFileName() + "\""; 
                    count++; 
                    auxReqBody[count] = "Content-Type: text/plain"; 
                    count++; 
                    auxReqBody[count] = ""; 
                    count++; 
                    auxReqBody[count] = par.StringValue; 
                    count++; 
                    break; 
                } 
                case ParamsStruct.ParamType.Parameter: 
                default: 
                { 
                    auxReqBody[count] = 
                      "Content-Dis-data; name=\"" + par.Name + "\""; 
                    count++; 
                    auxReqBody[count] = ""; 
                    count++; 
                    auxReqBody[count] = par.StringValue; 
                    count++; 
                    break; 
                } 
            } 
        } 
        auxReqBody[count] = boundary; 
        count++; 
        string requestBody = String.Join("\r\n",auxReqBody); 
        return requestBody;
    }

    #提交

    public void PostData ()
    { 
        //Set URL 
        Uri urlUri = new Uri(_URL); 
        //Encoding postData 
        ASCIIEncoding encoding = new ASCIIEncoding(); 
        string postData = this.GetPostData(); 
        byte[] buffer = encoding.GetBytes( postData ); 
        // Prepare web request... 
        HttpWebRequest myRequest = 
           (HttpWebRequest)WebRequest.Create(urlUri); 
        // We use POST ( we can also use GET ) 
        myRequest.Method = this._Method; 
        myRequest.AllowWriteStreamBuffering = true; 
        // Set the content type to a FORM 
        string auxContent = this._ContentType; 
        if (this._Boundary.Length > 0) 
            auxContent += "boundary=" + this._Boundary; 
        myRequest.ContentType = auxContent; 
        // Get length of content 
        myRequest.Accept = this._Accept; 
        myRequest.ContentLength = buffer.Length; 
        // Get request stream 
        Stream newStream = myRequest.GetRequestStream(); 
        // Send the data. 
        newStream.Write(buffer,0,buffer.Length); 
        // Close stream 
        newStream.Close(); 
        _myHttpWebResponse= (HttpWebResponse)myRequest.GetResponse(); 
        // Set the response to ResponseStream property 
        this._ResponseStream = _myHttpWebResponse.GetResponseStream();
    }

    完整的代码,可以通过以下的链接来下载:

    http://www.codeproject.com/Articles/17449/Send-a-content-type-multipart-form-data-request-fr

    Best regards,

    Cole Wu


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    2016年9月8日 7:07
    版主