简体   繁体   中英

How to download files with filename containing special characters using .Net WebClient

I am getting an error “400 – Bad Request” while using .Net WebClient to download files with filename containing certain characters:

For example if the file is named: 5L1XQE6FTest #.mp4 ; this generates an error.

If I remove the # sign the file is downloaded fine:

Here is my code:

public ActionResult DownloadVideoFile(string filepath)
{
    try
    {              
        filepath = "http://localhost:1832/VideoUploads/" + filepath;
        var type = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
        var path = Path.GetFileName(filepath);

        using (var client = new WebClient())
        {           
            var buffer = client.DownloadData(filepath);
            return File(buffer, type.ToString(), path);
        }
    }
    catch (Exception e)
    {
        var test = e.Message;
    }

    return null;    
}

I have no control over the filename that I am trying to download as files are user submitted.

When I Url encode the file I get a "Cannot find file" error:

using (var client = new WebClient())
{
    filepath = Url.Encode(filepath);
    var buffer = client.DownloadData(filepath);
    return File(buffer, type.ToString(), path);
}

Here is the path after URL encoding:

C:\\Program Files (x86)\\IIS Express\\http%3a%2f%2flocalhost%3a1832%2fVideoUploads%2f5L1XQE6FTest+%23.mp4'

How can I resolve the Bad Request error while downloading files with special or reserved characters?

At what point in your code is the exception actually being raised? WebClient should have no problem downloading any validly named resource (valid as in it actually functions as a URL). If the URL you're trying to use is in fact not a valid URL (because of the odd file name), URL encoding it might be sufficient to fix the issue.

However, you're also using the bad file name later as a parameter to File , and that's probably a bad idea. If this is where the exception is being raised, simply constructing your own filename, without the problematic characters, should be enough to solve the problem.

请用#23替换#,它将起作用。

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