一:Winform上传文件示例 /// 上传文件方法 /// /// 本地文件所在路径(包括文件) public void UploadFile(string filePath) {
try
{
//创建WebClient实例
WebClient webClient = new WebClient();
webClient.UploadFileCompleted += WebClient_UploadFileCompleted;
webClient.Credentials = CredentialCache.DefaultCredentials;
webClient.Headers.Add("Content-Type", "application/form-data");//注意头部必须是form-data
webClient.QueryString["HostNumebr"] = "30048";
//iispath 服务端上传文件的接口(http://192.xxx.xx.xx:8001/MDTool/UpLoadFiless)
webClient.UploadFileAsync(new Uri(iispath), "POST", filePath);
//string getPath = Encoding.GetEncoding("UTF-8").GetString(responseArray);
}
catch (Exception ex)
{
}
}
二:MVC接口示例
/// <summary>
/// 文件上传
/// </summary>
/// <returns></returns>
[HttpPost]
[AllowAnonymous]
public Task<string> UpLoadFiless()
{
var res = "1";
string fileName = "gene-data.xlsx";
string filePath = string.Empty;
string hostnumber = Request["HostNumebr"];
var strServerFilePath = Server.MapPath("~/MDExcel/" + hostnumber);
if (!Directory.Exists(strServerFilePath))
{
Directory.CreateDirectory(strServerFilePath);
}
filePath = Path.Combine(strServerFilePath, fileName);
try
{
if (Request.Files.Count > 0)
{
HttpPostedFileBase file = Request.Files[0];
file.SaveAs(filePath);
}
else
{
res = "0";
}
}
catch (Exception ex)
{
res = "-1";
}
return Task.FromResult(res);
}