简体   繁体   中英

Exception occurred during a WebClient request

WinForm Application Code-

FileSystemWatcher fsWatcher = new FileSystemWatcher();
fsWatcher.Created += new FileSystemEventHandler(OnCreated);

    public void OnCreated(object sender, FileSystemEventArgs e)
    {
        try
        {
            var wc = new WebClient();

            byte[] response = 
                    wc.UploadFile("http://localhost:54802/Home/ReceiveAudio/", 
                                  "POST", e.FullPath);
            string s = System.Text.Encoding.ASCII.GetString(response);
            MessageBox.Show(s);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

MVC Controller Action Method-

    [HttpPost]
    public JsonResult ReceiveAudio()
    {
        return Json("Success", JsonRequestBehavior.AllowGet);
    }

I'm getting error - An exception occurred during a WebClient request.

Any help?

In windows side:

private void uploadButton_Click(object sender, EventArgs e)
{
    var openFileDialog = new OpenFileDialog();
    var dialogResult = openFileDialog.ShowDialog();    
    if (dialogResult != DialogResult.OK) return;              
    Upload(openFileDialog.FileName);
}

private void Upload(string fileName)
{
    var client = new WebClient();
    var uri = new Uri("https://www.yoursite.com/UploadFile/");  
    try
    {
        client.Headers.Add("fileName", System.IO.Path.GetFileName(fileName));
        var data = System.IO.File.ReadAllBytes(fileName);
        client.UploadDataAsync(uri, data);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

In server side you should use WebApi:

[HttpPost]
public async Task<object> UploadFile()
{
    var file = await Request.Content.ReadAsByteArrayAsync();
    var fileName = Request.Headers.GetValues("fileName").FirstOrDefault();
    var filePath = "/upload/files/";
    try
    {
        File.WriteAllBytes(HttpContext.Current.Server.MapPath(filePath) + fileName, file);           
    }
    catch (Exception ex)
    {
        // ignored
    }

    return null;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM