直接上代码
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.IO; using System.Windows.Forms; namespace UploadImageFile { public partial class Form1 : Form { #region 全局变量 HttpHelper Http = new HttpHelper(); HttpItem item = null; HttpResult result = null; #endregion public Form1() { InitializeComponent(); } private void but_Upload_Click(object sender, EventArgs e) { #region 变量 byte[] UploadBuffers = null; string BoundStr = "-----------------------------7de1b519306dc";//根据抓包生成 StringBuilder UploadBuf = new StringBuilder(); #endregion #region 头部数据 UploadBuf.Append(BoundStr + "\r\n"); UploadBuf.Append(@"Content-Disposition: form-data; name=""file""; filename=""test.jpg""" + "\r\n"); UploadBuf.Append("Content-Type: image/jpeg\r\n\r\n"); byte[] HeadBytes = Encoding.ASCII.GetBytes(UploadBuf.ToString()); #endregion #region 图片数据 byte[] PicBytes = ImageToBytesFromFilePath(@"D:\test.jpg"); #endregion #region 尾部数据 UploadBuf.Clear(); UploadBuf.Append("\r\n" + BoundStr + "\r\n"); UploadBuf.Append(@"Content-Disposition: form-data; name=""id""" + "\r\n\r\n\r\n"); UploadBuf.Append(BoundStr + "\r\n" + @"Content-Disposition: form-data; name=""proxyurl""" + "\r\n\r\n\r\n"); UploadBuf.Append(BoundStr + "\r\n" + @"Content-Disposition: form-data; name=""jsmode""" + "\r\n\r\ntrue\r\n"); UploadBuf.Append(BoundStr + "\r\n" + @"Content-Disposition: form-data; name=""rule""" + "\r\n\r\nproductImageRule\r\n"); UploadBuf.Append(BoundStr + "--"); byte[] TailBytes = Encoding.ASCII.GetBytes(UploadBuf.ToString()); #endregion #region 数组拼接 UploadBuffers = ComposeArrays(HeadBytes, PicBytes); UploadBuffers = ComposeArrays(UploadBuffers, TailBytes); #endregion #region 上传 item = new HttpItem() { URL = "http://upload.alibaba.com/fileupload", Method = "POST", ContentType = "multipart/form-data; boundary=" + BoundStr.Substring(2), Referer = "http://upload.alibaba.com/fileupload.html", PostDataType = PostDataType.Byte, PostEncoding = Encoding.UTF8, PostdataByte = UploadBuffers }; result = Http.GetHtml(item); MessageBox.Show(result.Html); #endregion } #region 数组组合 public static byte[] ComposeArrays(byte[] Array1, byte[] Array2) { byte[] Temp = new byte[Array1.Length + Array2.Length]; Array1.CopyTo(Temp, 0); Array2.CopyTo(Temp, Array1.Length); return Temp; } #endregion #region 图片转Byte数组 private byte[] ImageToBytesFromFilePath(string FilePath) { using (MemoryStream ms = new MemoryStream()) { using (Image Img = Image.FromFile(FilePath)) { using (Bitmap Bmp = new Bitmap(Img)) { Bmp.Save(ms, Img.RawFormat); } } return ms.ToArray(); } } #endregion } }