使用webrequest上载文件
本文关键字:文件 上载 webrequest 使用 | 更新日期: 2023-09-27 18:08:50
我正在尝试将图像上传到图像主机http://uploads.im/
。
根据其简短的API http://uploads.im/apidocs
,这是一种实现这一点的方法:
http://uploads.im/api?upload=http://www.google.com/images/srpr/nav_logo66.png
注意,在这个例子中,他正在从互联网上传一张图片,而我正试图从我的电脑上传一个文件。
代码:
public ActionResult SaveUploadedFile()
{
//Converts the image i want to upload to a bytearray
Image postData = img;
byte[] byteArray = imageToByteArray(postData);
//Is this adress not correct maybe? Is there a way to test?
WebRequest wrq = WebRequest.Create("http://uploads.im/api?upload=");
wrq.Method = ("POST");
//Im thinking that here I need som code
//that specifys the file i want to upload (bytearray)
using (WebResponse wrs = wrq.GetResponse())
using (Stream stream = wrs.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
string json = reader.ReadToEnd();
tempJson = json;
}
}
请看!谢谢
EDIT,新代码:
string filepath = @"c:'Users'xxxx'Desktop'Bilder'images'blank.gif";
using (WebClient client = new WebClient())
{
client.UploadFile("http://uploads.im/api?upload", filepath);
}
我得到错误::底层连接关闭
尝试捕获编辑:
string filepath = @"c:'Users'xxxx'Desktop'sack.png";
using (WebClient client = new WebClient())
{
try
{
client.UploadFile("http://uploads.im/api?upload", filepath);
}
catch (Exception e)
{
throw new ApplicationException(e);
}
}
private void UploadImage(string filepath)
{
using(WebClient uploader = new WebClient())
{
try
{
uploader.UploadFile(new Uri("http://uploads.im/api?upload"), filepath);
}
catch(Exception ex)
{
MessageBox.Show("An error occured :('r'n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
我正在使用http://uploads.im/api?upload作为端点,因为在文档中读取时,它将被视为REQUEST
,并将自动检测图像的上传
然而,我自己尝试了这个代码,每次都断开连接,没有任何有意义的响应,只有The remote host unexpectedly closed the connection
。根据医生的说法,当出现问题时,你应该得到Bad request
。我联系了支持人员,希望他们能告诉我更多关于它的信息。(编辑:他们没有(