简体   繁体   English

如何使用.Net WebClient下载文件名包含特殊字符的文件

[英]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: 使用.Net WebClient下载文件名包含某些字符的文件时,出现错误“ 400 –错误的请求”:

For example if the file is named: 5L1XQE6FTest #.mp4 ; 例如,如果文件名为: 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: 这是URL编码后的路径:

C:\\Program Files (x86)\\IIS Express\\http%3a%2f%2flocalhost%3a1832%2fVideoUploads%2f5L1XQE6FTest+%23.mp4' 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). WebClient可以毫无问题地下载任何有效命名的资源(有效,因为它实际上起着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. 如果您尝试使用的URL实际上不是有效的URL(由于文件名是奇数),则对该URL进行编码可能足以解决问题。

However, you're also using the bad file name later as a parameter to File , and that's probably a bad idea. 但是,您稍后还会使用错误的文件名作为File的参数,这可能是一个坏主意。 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替换#,它将起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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