c# web服务器传图片不显示不出来的,无法在c#中使用httpwebrequest上传图片

我试图通过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 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 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 postParameters = new Dictionary();

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);

解决方法:

在我看来,你应该使用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;

}

来源:http://www.icode9.com/content-1-212001.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: C#HttpWebRequest是一个用于发送HTTP请求的类。它可以用于向Web服务器发送GET、POST、PUT、DELETE等请求,并获取服务器响应。以下是HttpWebRequest的用法: 1. 创建HttpWebRequest对象 使用HttpWebRequest.Create方法创建HttpWebRequest对象,如下所示: HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 其url是要请求的URL地址。 2. 设置请求方法 使用HttpWebRequest.Method属性设置请求方法,如下所示: request.Method = "GET"; 3. 设置请求头 使用HttpWebRequest.Headers属性设置请求头,如下所示: request.Headers.Add("User-Agent", "Mozilla/5.0"); 4. 设置请求参数 使用HttpWebRequest.GetRequestStream方法获取请求流,然后将请求参数写入请求流,如下所示: using (Stream stream = request.GetRequestStream()) { byte[] data = Encoding.UTF8.GetBytes("param1=value1&param2=value2"); stream.Write(data, 0, data.Length); } 5. 发送请求并获取响应 使用HttpWebRequest.GetResponse方法发送请求并获取响应,如下所示: using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (Stream stream = response.GetResponseStream()) { StreamReader reader = new StreamReader(stream, Encoding.UTF8); string result = reader.ReadToEnd(); } } 其result就是服务器响应的内容。 以上就是C#HttpWebRequest的用法。 ### 回答2: 我很抱歉,您没有提供问题或者主题,因此我无法提供相关的回答。请您给出更具体的问题或者主题,我会尽力为您提供满意的答案。感谢您的理解! ### 回答3: 抱歉,您没有提供问题或背景,无法提供回答。请提供问题或背景以获取更好的回答。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值