.net core上传文件、.net core接收文件上传

我要做一个winform程序,上传文件到.net8的文件上传接口
winform

/// <summary>
/// 选择图片上传
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void btnExtract_Click(object sender, EventArgs e)
{
    try
    {
        var fileDialog = new OpenFileDialog();//创建打开页面
        fileDialog.Multiselect = false;//不开启多选
        fileDialog.Title = "请选择图片";//设置标题
        fileDialog.Filter = "images|*.png|images|*.jpg|images|*.gif|images|*.jpeg|images|*.bmp";//文件格式
        if (fileDialog.ShowDialog() == DialogResult.OK)
        {
            btnExtract.Enabled = false;
            string filePath = fileDialog.FileName;//原始图片路径C:\Users\jay.star\Desktop\02.png
            var ext = Path.GetExtension(filePath);//.png
            var fdir = Path.GetDirectoryName(filePath);//C:\Users\jay.star\Desktop\
            var fileName = Path.GetFileName(filePath);//02.png
            byte[] fileBytes = Utils.GetFileBytes(filePath);//文件转byte[]//上传接口地址
            string serverUrl = "http://192.168.9.29:32831/Upload/UploadFiles";            //多个文件时,重复多次添加到content中。
            //fileContent的Headers信息中的Name必须要和接口参数的名字一样。
            var fileContent = new ByteArrayContent(fileBytes);
            fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
            {
                Name = "file",
                FileName = fileName,
            };

            //var fileContent2 = new ByteArrayContent(fileBytes);
            //fileContent2.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
            //{
            //    Name = "file",
            //    FileName = fileName,
            //};

            var content = new MultipartFormDataContent();
            content.Add(fileContent);
            //content.Add(fileContent2);

            var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, serverUrl);
            httpRequestMessage.Content = content;
            var httpClient = new HttpClient();
            var httpResponseMessage = httpClient.SendAsync(httpRequestMessage).Result;
            if (httpResponseMessage.IsSuccessStatusCode)
            {
                using (var contentStream = await httpResponseMessage.Content.ReadAsStreamAsync())
                {
                    using (StreamReader sw = new StreamReader(contentStream))
                    {
                        string res2 = sw.ReadToEnd();
                        txtRes.Text += "\n" + "结果:" + res2;
                    }
                }
            }
        }
    }
    catch (Exception ex)
    {
        txtRes.Text = ex.ToString();
    }
    btnExtract.Enabled = true;
}

.net8接口

/// <summary>
/// http://192.168.9.29:32831/Upload/UploadFiles
/// 多个文件:IFormFileCollection file
/// 单个文件:IFormFile file
/// 参数名字:file,必须和参数一致
/// </summary>
/// <returns></returns>
[HttpPost]
public JsonResult UploadFiles(IFormFileCollection file)
{
    ApiResult<List<string>> result = new ApiResult<List<string>>()
    {
        data = new List<string>(),
        errorCode = "0",
        message = "success"
    };
    try
    {
        var webRootPath = this.env.ContentRootPath;//获取项目路径
        var files2 = HttpContext.Request.Form.Files;//也可以使用这种来获取文件列表
        var pathList = Utils.UploadFiles(webRootPath, file);
        result.data = pathList;
    }
    catch (Exception ex)
    {
        result.errorCode = "-1";
        result.message = ex.Message;
    }
    return new JsonResult(result);
}

保存文件

/// <summary>
/// 上传文件
/// E:\Demos\XCGWebApp\UploadFile\
/// </summary>
/// <param name="webRootPath">系统目录</param>
/// <param name="files">文件列表</param>
public static List<string> UploadFiles(string webRootPath, IFormFileCollection files)
{
    List<string> filesPathList = new List<string>();
    var fileDir = $"UploadFile\\";
    var dirPath = Path.Combine(webRootPath, fileDir);
    if (!Directory.Exists(dirPath))
    {
        Directory.CreateDirectory(dirPath);
    }
    long timeStamp = (long)(DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;
    foreach (var file in files)
    {
        var fname = timeStamp + "_" + file.FileName;
        var fileExtension = Path.GetExtension(file.FileName);// 文件后缀
        var fileSize = file.Length;// 文件大小 1024 * 1024 * 10 = 10M
        string filePath = dirPath + fname;
        using (FileStream fs = File.Create(filePath))
        {
            file.CopyTo(fs);
            fs.Flush();
        }
        filesPathList.Add("UploadFile/" + fname);
    }
    return filesPathList;
}

文件转byte[]

/// <summary>
/// 将文件转换成byte[] 数组
/// </summary>
/// <param name="fileUrl">文件路径文件名称</param>
/// <returns>byte[]</returns>
public static byte[] GetFileBytes(string fileUrl)
{
    using (FileStream fs = new FileStream(fileUrl, FileMode.Open, FileAccess.Read))
    {
        byte[] buffur = new byte[fs.Length];
        fs.Read(buffur, 0, (int)fs.Length);
        return buffur;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章