通过HTTP Post上传文件-效率

时间:2018-09-13 13:31:57

标签: c# multithreading http post webclient

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

我现在正在使用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效率最高?您有什么建议吗?

1 个答案:

答案 0 :(得分:0)

如果无法将文件分组,则需要一个一个地上传它们。如果可以对它们进行分组,则建议创建一个文件(如果文件不明显),该文件将包含所需的文件路径,请压缩文件,然后上传压缩文件,将其解压缩到服务器上,然后将文件移至所需位置位置。不过,您将需要注意安全性。

WebClient实现FTP上传,请参阅:Upload file to FTP using C#

相关问题