C#后端WebApi,前端Upload文件上传

Posted 何以解忧 `唯有暴富

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#后端WebApi,前端Upload文件上传相关的知识,希望对你有一定的参考价值。

参考资料

https://blog.csdn.net/gskull/article/details/82758553

https://blog.csdn.net/zm_miner/article/details/95083719

asp.net core webapi文件上传

最近开发一个新项目,使用了asp.net core 2.0,采用webapi开发后台,postgresql为数据库。最先来的问题就是上传文件的问题。

https://www.cnblogs.com/podolski/p/7795168.html

前端的拦截器

// 配置拦截器
request.interceptors.request.use(async (url, options) => {
  const headers = {}

  if (abp.auth.getToken()) {
    headers.Authorization = `Bearer ${  abp.auth.getToken()}`;
  }

  headers['.AspNetCore.Culture'] = abp.utils.getCookieValue('Abp.Localization.CultureName');
  headers['Abp.TenantId'] = abp.multiTenancy.getTenantIdCookie();
    return {
      url,
      options: { ...options, headers }
    }
})

试着从Request payload取文件,得自己实现,代码

<Upload
                  disabled={pathIsNull} 
                  name={"file"}
                  action = {"/api/services/app/AppUpdateTaskService/UpdateAppUpdateTasksFile"}
                >
                <Button disabled={pathIsNull} type="primary" icon={<UploadOutlined/>}>Click to Upload</Button>
              </Upload>

或者

<ProForm.Item>
        <Upload action='路径'
            multiple={false}
            beforeUpload={beforeUploadHandle} 
            onRemove={fileRemove}>
            <Button>上传文件</Button>
        </Upload>
      </ProForm.Item>

 const beforeUploadHandle = (file:UploadFile,fileList:UploadFile[]) =>{
    console.log(file);
    //好用
    const formData = new FormData();
    formData.append('file', file);
    request('/api/services/app/AppUpdateTaskService/UpdateAppUpdateTasksFile', { method: 'post', data: formData });
  }

 后台这个可以

[HttpPost]
public String UpdateAppUpdateTasksFile([FromForm] IFormCollection formCollection)
{
    System.Console.WriteLine("");
    System.Console.WriteLine("UpdateAppUpdateTasksFile");
    System.Console.WriteLine("");
    String result = "Fail";
    if (formCollection.ContainsKey("user"))
    {
        var user = formCollection["user"];
    }
    FormFileCollection fileCollection = (FormFileCollection)formCollection.Files;
    foreach (IFormFile file in fileCollection)
    {
        StreamReader reader = new StreamReader(file.OpenReadStream());
        String content = reader.ReadToEnd();
        String name = file.FileName;
        String filename = @"D:/" + name;
        if (System.IO.File.Exists(filename))
        {
            System.IO.File.Delete(filename);
        }
        using (FileStream fs = System.IO.File.Create(filename))
        {
            // 复制文件
            file.CopyTo(fs);
            // 清空缓冲区数据
            fs.Flush();
        }
        result = "Success";
    }
    return result;
}

以上是关于C#后端WebApi,前端Upload文件上传的主要内容,如果未能解决你的问题,请参考以下文章

HTML 表单文件上传不上传文件

webAPI+angularJS文件上传和下载

硬核!文件上传(upload_labs)之一命通关技巧

[BUUOJ记录] [ACTF2020 新生赛]Upload

#yyds干货盘点#前端如何通过antdv组件上传文件

如何在 WebAPI 后端 C# 上接收 JSON 数据?