.netcore 文件上傳轉爲base64位字符串

  .netcore文件上傳Api接口,和正常的webForm提交相似,只是用postman測試接口時,記得給form表單命名,不然獲取上傳文件數量一直爲0web

  後端代碼後端

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測試上傳api

相關文章
相關標籤/搜索