c# - 使用 webrequest 上传文件

标签 c# webrequest

我正在尝试将图像上传到图像主机 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);
    }
}

最佳答案

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

关于c# - 使用 webrequest 上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24238166/

相关文章:

c# - 如何获取网页的文本?

C# 在程序启动时实例化/初始化对象

c# - Entity Framework 插入多对多创建重复数据

javascript - Wcf REst 服务无法接受来自 Angular JS 应用程序的输入值

c# - 如何获取动态添加到 Windows 窗体 C# 中的控件的值?

c# WebRequest 使用 WebBrowser cookie

javascript - 在外部域(C# 或 Javascript)上提交表单

c# - 将图像从 Url 异步加载到 PictureBox

javascript - 安全的 Javascript 代码

c# - 使用 C# 进行远程 HTTP 发布