我在form1上有一個pictureBox和一個按鈕。當按鈕被點擊時,它應該將文件上傳到服務器。現在我正在使用下面的方法。首先在本地保存圖像,然後上傳到服務器:從PictureBox將圖像上傳到服務器
Bitmap bmp = new Bitmap(this.form1.pictureBox1.Width, this.form1.pictureBox1.Height);
Graphics g = Graphics.FromImage(bmp);
Rectangle rect = this.form1.pictureBox1.RectangleToScreen(this.form1.pictureBox1.ClientRectangle);
g.CopyFromScreen(rect.Location, Point.Empty, this.form1.pictureBox1.Size);
g.Dispose();
bmp.Save("filename", ImageFormat.Jpeg);
然後上傳該文件:
using (var f = System.IO.File.OpenRead(@"F:\filename.jpg"))
{
HttpClient client = new HttpClient();
var content = new StreamContent(f);
var mpcontent = new MultipartFormDataContent();
content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
mpcontent.Add(content);
client.PostAsync("http://domain.com/upload.php", mpcontent);
}
在StreamContent我不能使用位圖型。如何直接從pictureBox流式傳輸圖像,而不是直接將其保存爲文件?
我想出使用MemoryStream的下面的代碼,但上傳的文件大小是0使用這種方法。爲什麼?
byte[] data;
using (MemoryStream m = new MemoryStream())
{
bmp.Save(m, ImageFormat.Png);
m.ToArray();
data = new byte[m.Length];
m.Write(data, 0, data.Length);
HttpClient client = new HttpClient();
var content = new StreamContent(m);
var mpcontent = new MultipartFormDataContent();
content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
mpcontent.Add(content, "file", filename + ".png");
HttpResponseMessage response = await client.PostAsync("http://domain.com/upload.php", mpcontent);
//response.EnsureSuccessStatusCode();
string body = await response.Content.ReadAsStringAsync();
MessageBox.Show(body);
}
保存將圖像傳送到MemoryStream,然後上傳支持MemoryStream的字節。 – EricLaw
讓我檢查,謝謝 – user969068
我很抱歉,但我無法弄清楚如何在MemoryStream中保存BMP。 data = new byte [bmp.NOTSURE]; m.Write(data,0,data.Length); – user969068