使用webrequest上传文件

时间:2014-06-16 07:01:24

标签: c# webrequest

我正在尝试将图片上传到ima​​gehost 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;
    }
}

请看!谢谢!

编辑,新代码:

string filepath = @"c:\Users\xxxx\Desktop\Bilder\images\blank.gif";

using (WebClient client = new WebClient())
{
    client.UploadFile("http://uploads.im/api?upload", filepath);
}

我收到错误::基础连接已关闭

使用try catch编辑:

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);
    }
}

1 个答案:

答案 0 :(得分:2)

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。我联系了支持人员,希望他们可以告诉我更多相关信息。 (编辑:他们没有)