首页 > 解决方案 > 通过 HTTP Post 上传文件 - 效率

问题描述

通过http post将文件上传到服务器的最有效方法是什么?

我现在正在使用 WebClient 和线程:

public static void Uploadfile(string file_path, string SERVER_URL)
    {
        string filename = file_path;//Asign a value anyway in case of error.
        try
        {
                filename = Path.GetFileName(file_path);

                //Parameter for pass the name of the file
                NameValueCollection parameters= new NameValueCollection();
                parameters.Add("file", filename);
                WebClient client = new WebClient();
                //PUT Request
                client.QueryString = parameters;
                byte[] rawResponse = client.UploadFile(SERVER_URL, "POST", file_path);
                Console.WriteLine(filename + " Uploaded!");
                client.Dispose();
        }
        catch (Exception err)
        {
            Console.WriteLine(filename + " NOT uploaded: " + err.Message);
        }
    }

我这样调用线程中的函数:

for(xxx)
    tasks.Add(Task.Run(() => Uploadfile(file_path, SERVER_URL)));

我为每个文件打开一个实例,这很糟糕吗?WebClient 是最高效的?你有什么建议吗?

标签: c#multithreadinghttppostwebclient

解决方案


如果您无法对文件进行分组,那么您将需要一个接一个地上传它们。如果您可以将它们分组,那么建议创建一个包含所需文件路径的文件,如果不明显,压缩文件,上传压缩文件,在服务器上解压缩并将文件移动到他们想要的地点。不过,您需要注意安全性。

WebClient实现FTP上传,见:Upload file to FTP using C#


推荐阅读