Download file from webrequest

I am trying to upload an image to imagehost http://uploads.im/.

According to its very short API, http://uploads.im/apidocsthis is the way to do this:

http://uploads.im/api?upload=http://www.google.com/images/srpr/nav_logo66.png

Please note that in this example it downloads an image from the Internet, and Im trying to download a file from my computer.

the code:

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

Please look! Thank!

EDIT, new code:

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

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

I get an error :: Closed connection closed

EDIT with 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);
    }
}
+4
source share
1 answer
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 - . , . (: )

+2

Source: https://habr.com/ru/post/1544706/


All Articles