网站是php写的,我是用c#模拟请求的
我需要以multipart/form-data的形式上传图片,图片也确实传上去了,但是返回值跟在网站上直接上传后的结果不一样,网站技术跟我说图片是直接转成byte上传的,没做处理,我也是直接上传的,但是在fiddler获取的图片流不一样,他的每个图片流开头都是这样的
而我的不是,怎么办?
这个好像是代码的问题,后来就可以了
用postman这种第三方工具试下,先确认接口有无问题。
c#的multipart/form-data图片上传,我感觉用httpclient好一点。
接口没问题的,我用fiddler获取的
调这个方法:
/// <summary>
/// HTTP POST方式请求数据
/// </summary>
/// <param name="url">URL</param>
/// <param name="param">POST的数据</param>
/// <param name="fileByte">图片Byte</param>
/// <returns></returns>
public static string Post(string url, IDictionary<string, string> param, byte[] fileByte)
{
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
wr.ReadWriteTimeout = 30 * 1000;
wr.ContentType = "multipart/form-data; boundary=" + boundary;
wr.Method = "POST";
Stream rs = null;
try
{
rs = wr.GetRequestStream();
}
catch { return "无法连接.请检查网络."; }
string responseStr = null;
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
foreach (string key in param.Keys)
{
rs.Write(boundarybytes, 0, boundarybytes.Length);
string formitem = string.Format(formdataTemplate, key, param[key]);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
rs.Write(formitembytes, 0, formitembytes.Length);
}
rs.Write(boundarybytes, 0, boundarybytes.Length);
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
string header = string.Format(headerTemplate, "Image", "1.jpg", "application/octet-stream");
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
rs.Write(headerbytes, 0, headerbytes.Length);
rs.Write(fileByte, 0, fileByte.Length);
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--");
rs.Write(trailer, 0, trailer.Length);
rs.Close();
WebResponse wresp = null;
try
{
wresp = wr.GetResponse();
Stream stream2 = wresp.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
responseStr = reader2.ReadToEnd();
}
catch (Exception) { }
finally
{
if (wresp != null)
{
wresp.Close();
wresp = null;
}
wr.Abort();
wr = null;
}
return responseStr;
}
您这个不行啊,返回结果提示图片文件为空
@美。: 图片有转换成 byte[] 吗
@三人乐乐: 有呀