.net core webapi 文件上传

这篇博客详细介绍了如何在.NET Core WebAPI中实现文件上传功能,包括后端代码实现(支持单个文件上传)和前端Ant Design Vue组件的使用。后端通过接收IFormFile参数,将文件保存到服务器,并返回上传结果。前端使用A-Upload组件进行文件选择和上传,通过axios的postAction方法发送请求。博客展示了完整的代码示例及实际上传效果。
摘要由CSDN通过智能技术生成

.net core webapi 文件上传

技术架构:.net core + antd vue
直接上代码!!!
1.后端代码实现方法(这种写法仅支持单个文件上传):

public IActionResult uploadFileForAsset(IFormFile file) 
{
    try
    {
        // 服务器将要存储文件的路径
        string path = "/assetImg/";
        //var Folder = AppDomain.CurrentDomain.BaseDirectory + path; //项目默认路径
        var Folder = "C:/adminFile" + path;
        if (Directory.Exists(Folder) == false)//如果不存在就创建file文件夹
        {
            Directory.CreateDirectory(Folder);
        }
        StreamReader reader = new StreamReader(file.OpenReadStream());
        String content = reader.ReadToEnd();
        String name = file.FileName; // 获取文件名
        String filename = Folder + 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();
        }

        return new JsonResult(new { success = true, msg = "上传成功!", result = path+name });
    }
    catch (Exception ex)
    {
        return new JsonResult(new { success = false, msg = "上传失败!", result = ex.Message });
    }
    
}

2.前端页面实现:

<template>
	<a-upload name="file" :multiple="true" action="" :headers="headers" :customRequest="uploadFileForAsset" :showUploadList="false">
		<a-button> <a-icon type="upload" />上传</a-button>
	</a-upload>
</template>
data() {
return {
  headers: {
    authorization: 'authorization-text',
  },
},
methods: {
	uploadFileForAsset(data) {
	  const formData = new FormData()
	  formData.append('file', data.file)
	  postAction(this.url.uploadFileForAsset, formData).then((res) => {
	    if (res.success) {
	      this.$message.success(res.msg)
	    } else {
	      this.$message.error(res.msg)
	    }
	  })
	},
}

3.上传效果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值