• 00
  • :
  • 00
  • :
  • 00

webAPI 上传文件

服务端代码:

[HttpPost]
public APIResult PostFormFile(string path)
{
    try
    {
        //如果路径不存在,创建路径
        if (!Directory.Exists(path))
            return new APIResult()
            {
                status = -1,
                Message = "文件上传失败",
                Data = "路径不存在"
            };

        HttpFileCollection files = HttpContext.Current.Request.Files;
        List<string> errMsg = new List<string>();
        foreach (string key in files.AllKeys)
        {
            string fileName = System.IO.Path.Combine(path, files[key].FileName);
            if (System.IO.File.Exists(fileName))
                errMsg.Add("文件已存在:" + fileName);
        }
        if (errMsg.Count > 0)
        {
            return new APIResult()
            {
                status = -1,
                Message = "文件上传失败,文件已存在",
                Data = String.Join(System.Environment.NewLine, errMsg)
            };
        }
        foreach (string key in files.AllKeys)
        {
            HttpPostedFile file = files[key];

            if (string.IsNullOrEmpty(file.FileName) == false)
            {
                //int length = file.ContentLength;
                //if (length > 2097152)
                //{
                //    throw new CustomException("上传文件超过2M,请将上传文件大小控制在2M内,谢谢");
                //}
                //string extension = file.FileName.Substring(file.FileName.LastIndexOf('.')).ToLower();
                //if (extension != ".bmp" && extension != ".jpg" && extension != ".jpeg" && extension != ".png")
                //{
                //    throw new CustomException("上传文件扩展名不正确,请上传bmp,jpg,jpeg,png格式的图片");
                //}

                //name = DateTime.Now.ToStringByDatetime(DateTimeType.yyyyMMddHHmmss) + extension;
                ////LoginVerifyModels usermodel = GetVerifyModel();
                //string username = GetVerifyString();
                //if (!string.IsNullOrEmpty(username))
                //{
                //    name = username + extension;
                //}
                file.SaveAs(System.IO.Path.Combine(path, file.FileName));
            }
        }

        return new APIResult()
        {
            status = 0,
            Message = "文件上传成功"
        };
    }
    catch (Exception ex)
    {
        return new APIResult()
        {
            status = -1,
            Message = "文件上传发生异常",
            Data = ex.Message
        };
    }
}

客户端代码:

private void button1_Click(object sender, EventArgs e)
{

    string fileName = textBox1.Text;
    string url = txt_URL.Text;

    WebClient client = new WebClient();
    client.Credentials = CredentialCache.DefaultCredentials;
    client.Headers.Add("Content-Type", "application/form-data");//注意头部必须是form-data

    //client.QueryString["path"] = "d:\\test";
    client.UploadFileCompleted += (obj, arg) =>
    {
        if (arg.Error == null)
            MessageBox.Show("上传成功");
        else
            MessageBox.Show("上传失败:" + arg.Error.Message);
    };

    client.UploadProgressChanged += (obj, arg) =>
    {
        var p = arg.BytesSent * 100.0 / arg.TotalBytesToSend;
        //var rate = Math.Round(p, 2);
        Console.WriteLine("已上传:" + p.ToString("F2") + "%");
    };
    client.UploadFileAsync(new Uri(url), "POST", fileName);

}

 

posted @ 2021-02-18 14:23  Garson_Zhang  阅读(413)  评论(0编辑  收藏  举报