.netcore 文件上传转为base64位字符串

时间:2022-04-14 22:59:23

  .netcore文件上传Api接口,和正常的webForm提交类似,只是用postman测试接口时,记得给form表单命名,否则获取上传文件数量一直为0

  后端代码

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MyApiCommon;

namespace MyApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class FileController : ControllerBase
    {

        [HttpPost]
        [Route("postfile")]
        public string UploadAsync()
        {
            try
            {
                var files = HttpContext.Request.Form.Files;
                if (files.Count < 0)
                    return "请上传文件";
                long fileSize = files.Sum(f => f.Length) / 1024;//由字节转为kb
                Stream fs = files[0].OpenReadStream();//将文件转为流
                return Base64Convert.FileToBase64(fs);

            }
            catch (Exception ex)
            {
                return ex.Message;
            }


        }
    }
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;


namespace MyApiCommon
{
    public class Base64Convert
    {
        /// <summary>
        ///  文件转换成Base64字符串
        /// </summary>
        /// <param name="fs">文件流</param>
        /// <returns></returns>
        public static String FileToBase64(Stream  fs)
        {
            string strRet = null;

            try
            {
                if (fs == null) return null;
                byte[] bt = new byte[fs.Length];
                fs.Read(bt, 0, bt.Length);
                strRet = Convert.ToBase64String(bt);
                fs.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return strRet;
        }

        /// <summary>
        /// Base64字符串转换成文件
        /// </summary>
        /// <param name="strInput">base64字符串</param>
        /// <param name="fileName">保存文件的绝对路径</param>
        /// <returns></returns>
        public static bool Base64ToFileAndSave(string strInput, string fileName)
        {
            bool bTrue = false;

            try
            {
                byte[] buffer = Convert.FromBase64String(strInput);
                FileStream fs = new FileStream(fileName, FileMode.CreateNew);
                fs.Write(buffer, 0, buffer.Length);
                fs.Close();
                bTrue = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return bTrue;
        }
    }
}

  使用postman测试上传

.netcore 文件上传转为base64位字符串