我试图将图像发送到我正在使用当前程序的远程服务器。我如何做到这一点首先必须将图像保存到用户的工作站,然后我存储该位置并将其传递给我的方法,以便将其传递给我的服务器。
但是,当我运行代码以传递图像时,我收到一条错误消息,指出我的文件类型不受支持。
这是我的代码的一个运行:
public static void HttpUploadFile(string url, string file, string paramName, string contentType, NameValueCollection nvc)
{
Console.Write(string.Format("Uploading {0} to {1}", file, url));
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.ContentType = "multipart/form-data; boundary=" + boundary;
wr.Method = "POST";
wr.KeepAlive = true;
wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
Stream rs = wr.GetRequestStream();
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
foreach (string key in nvc.Keys)
{
rs.Write(boundarybytes, 0, boundarybytes.Length);
string formitem = string.Format(formdataTemplate, key, nvc[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, paramName, file, contentType);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
rs.Write(headerbytes, 0, headerbytes.Length);
FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
rs.Write(buffer, 0, bytesRead);
}
fileStream.Close();
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
rs.Write(trailer, 0, trailer.Length);
rs.Close();
WebResponse wresp = null;
try
{
wresp = wr.GetResponse();
Stream stream2 = wresp.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
Console.Write(string.Format("File uploaded, server response is: {0}", reader2.ReadToEnd()));
}
catch (Exception ex)
{
Console.Write("Error uploading file", ex);
if (wresp != null)
{
wresp.Close();
wresp = null;
}
}
finally
{
wr = null;
}
}
我这样调用方法:
NameValueCollection nvc = new NameValueCollection();
nvc.Add("id", "TTR");
nvc.Add("btn-submit-photo", "Upload");
HttpUploadFile("http://WebSiteLocation.com/images/uploadimage.html", sfd.ToString(),"image", "image/jpeg", nvc);
在上述方法中,sfd 与我用来保存图像的保存文件对话框有关。错误是这样的:
不支持给定路径的格式。
在这一行中突出显示:
FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
我认为上面的代码可以很好地发送任何文件,这就是为什么我很困惑这种情况正在发生。
任何人都可以看到原因吗?我花了一段时间看这个,我认为需要一双新的眼睛和大脑。
为了完成,我打电话时得到的字符串sfc.ToString()
是这样的:
System.Windows.Forms.SaveFileDialog:标题:文件名:C:\Users\MyComputer\Desktop\Img.png