【问题标题】:Not able to upload image using httpwebrequest in c#无法在 c# 中使用 httpwebrequest 上传图片
【发布时间】:2014-12-26 04:19:26
【问题描述】:

我正在尝试通过 API 以编程方式将图像上传到另一台服务器。 API 要求我上传字节数组中的图像,以便在字段中发送:“image_content”。

我的实现和调用代码如下。 Web 请求到达服务器,但服务器响应我的 Web 请求中不存在该图像。

当我运行以下代码时,我收到错误消息,即请求中不存在图像。我在这里错过了什么?

public static class FormUpload
{
    private static readonly Encoding encoding = Encoding.UTF8;
    public static HttpWebResponse MultipartFormDataPost(string postUrl, string userAgent, Dictionary<string, object> postParameters)
    {
        string formDataBoundary = String.Format("----------{0:N}", Guid.NewGuid());
        string contentType = "multipart/form-data; boundary=" + formDataBoundary;

    byte[] formData = GetMultipartFormData(postParameters, formDataBoundary);

    return PostForm(postUrl, userAgent, contentType, formData);
}
private static HttpWebResponse PostForm(string postUrl, string userAgent, string contentType, byte[] formData)
{
    HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;

    if (request == null)
    {
        throw new NullReferenceException("request is not a http request");
    }

    // Set up the request properties.
    request.Method = "POST";
    request.ContentType = contentType;
    request.UserAgent = userAgent;
    request.ContentLength = formData.Length;


    // Send the form data to the request.
    using (Stream requestStream = request.GetRequestStream())
    {
        requestStream.Write(formData, 0, formData.Length);
        requestStream.Close();
    }

    return request.GetResponse() as HttpWebResponse;
}

private static byte[] GetMultipartFormData(Dictionary<string, object> postParameters, string boundary)
{
    Stream formDataStream = new System.IO.MemoryStream();
    bool needsCLRF = false;

    foreach (var param in postParameters)
    { 
        if (param.Value is FileParameter)
        {
            FileParameter fileToUpload = (FileParameter)param.Value;

            // Add just the first part of this param, since we will write the file data directly to the Stream
            string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: {3}\r\n\r\n",
                boundary,
                param.Key,
                fileToUpload.FileName ?? param.Key,
                fileToUpload.ContentType ?? "application/octet-stream");

            formDataStream.Write(encoding.GetBytes(header), 0, encoding.GetByteCount(header));

            // Write the file data directly to the Stream, rather than serializing it to a string.
            formDataStream.Write(fileToUpload.File, 0, fileToUpload.File.Length);
        }
        else
        {
            string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}",
                boundary,
                param.Key,
                param.Value);
            formDataStream.Write(encoding.GetBytes(postData), 0, encoding.GetByteCount(postData));
        }
    }

    // Add the end of the request.  Start with a newline
    string footer = "\r\n--" + boundary + "--\r\n";
    formDataStream.Write(encoding.GetBytes(footer), 0, encoding.GetByteCount(footer));

    // Dump the Stream into a byte[]
    formDataStream.Position = 0;
    byte[] formData = new byte[formDataStream.Length];
    formDataStream.Read(formData, 0, formData.Length);
    formDataStream.Close();

    return formData;
}

public class FileParameter
{
    public byte[] File { get; set; }
    public string FileName { get; set; }
    public string ContentType { get; set; }
    public FileParameter(byte[] file) : this(file, null) { }
    public FileParameter(byte[] file, string filename) : this(file, filename, null) { }
    public FileParameter(byte[] file, string filename, string contenttype)
    {
        File = file;
        FileName = filename;
        ContentType = contenttype;
    }
}

}

调用上述函数的代码是:

// Read file data
FileStream fs = new FileStream("c:\\myimage.jpeg", FileMode.Open, FileAccess.Read);
byte[] data = new byte[fs.Length];
fs.Read(data, 0, data.Length);
fs.Close();

// Generate post objects
Dictionary<string, object> postParameters = new Dictionary<string, object>();
postParameters.Add("image_content",data);

// Create request and receive response
string postURL = "myurl";
string userAgent = "Mozilla";
HttpWebResponse webResponse = FormUpload.MultipartFormDataPost(postURL, userAgent, postParameters);

// Process response
StreamReader responseReader = new StreamReader(webResponse.GetResponseStream());
string fullResponse = responseReader.ReadToEnd();
webResponse.Close();
Response.Write(fullResponse);

【问题讨论】:

标签: c#


【解决方案1】:

在我看来,您应该使用 MultipartFormDataContent 类,因为它“为使用 multipart/form-data MIME 类型编码的内容提供容器。”。试试这个

    public static HttpWebResponse MultipartFormDataPost(string postUrl, string userAgent, byte[] data)
    {
        string contentType;
        byte[] formData = Program.GetMultipartFormData(data, out contentType);  
        return PostForm(postUrl, userAgent, contentType, formData);
    }

    public static byte[] GetMultipartFormData(byte[] data, out string contentType)
    {
        var byteArrayContent = new ByteArrayContent(data);
        byteArrayContent.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
        byteArrayContent.Headers.Add("image_content", "myimage.jpeg");

        var content = new MultipartFormDataContent(String.Format("----------{0:N}", Guid.NewGuid())) { byteArrayContent };
        contentType = content.Headers.ContentType.ToString();

        return content.ReadAsByteArrayAsync().Result;
    }

【讨论】:

    【解决方案2】:

    我能够通过使用 stackoverflow 问题Upload file through c# using JSON request and RestSharp 中提到的 RestSharp Api 来解决问题。

    【讨论】:

      【解决方案3】:

      你所有的代码都很好,但你忘了给你的参数编码

      试试这个

      string postData = string.Format("--{0}\r\nContent-Disposition: 
      form-data; name=\"{1}\"\r\n\r\n{2}",
                      boundary,
                      HttpUtility.UrlEncode(param.Key),
                      HttpUtility.UrlEncode(param.Value));
      

      如果是二进制数据

      HttpUtility.UrlEncode(Convert.ToBase64String(byte[]))
      

      尝试使用此代码在您的请求中添加参数

      NameValueCollection outgoingQueryString = HttpUtility.ParseQueryString(String.Empty);
      outgoingQueryString.Add("uname", "username");
      outgoingQueryString.Add("pname", "password");
      string postdata = outgoingQueryString.ToString();
      

      并在您的请求中写入此 postdata

      【讨论】:

        猜你喜欢
        • 2012-08-19
        • 2011-07-18
        • 2020-06-26
        • 1970-01-01
        • 2012-09-15
        • 2018-12-14
        • 2013-12-27
        • 2012-12-31
        • 2018-10-23
        相关资源
        最近更新 更多