c# - 通过 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 是最高效的?你有什么建议吗?
解决方案
如果您无法对文件进行分组,那么您将需要一个接一个地上传它们。如果您可以将它们分组,那么建议创建一个包含所需文件路径的文件,如果不明显,压缩文件,上传压缩文件,在服务器上解压缩并将文件移动到他们想要的地点。不过,您需要注意安全性。
WebClient实现FTP上传,见:Upload file to FTP using C#
推荐阅读
- flask - 无法从本地 python 文件导入模型
- javascript - 从 v-text-field Vue 中删除空格
- javascript - 如何在异步功能中获取更新的道具?
- java - 在 Angular 中的任何请求之前询问服务器 api
- php - “帐户登录不正确或您的帐户暂时被禁用。请稍候,稍后再试。”}
- javascript - 是否可以在 :after 仅使用 CSS 后嵌入超链接?
- python - Python:在熊猫数据框中选择匹配二月到当前月份的行
- windows - Jupyter Notebook Kernel 在特定环境下死机
- google-cloud-platform - 无法从 Google Cloud Function 访问存储在 Secrets Manager 中的密钥
- reactjs - 状态变化不反映反应中的子组件