C# webApi上传图片 代码篇

十年河东,十年河西,莫欺少年穷

学无止境,精益求精

代码篇,不多说

如下:

C# webApi上传图片 代码篇_C# webApi上传图片 代码篇C# webApi上传图片 代码篇_C# webApi上传图片 代码篇_02
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;

namespace FileUp.Controllers
{
    public class FileController : ApiController
    {
        [HttpPost]
        public async Task<string> UploadFileStream()
        {
            string returns = string.Empty;
            string fileType = "ss";//要创建的子文件夹的名字
            var uploadPath = "~/upload";
            string filePath = System.Web.HttpContext.Current.Server.MapPath(uploadPath + "/" + fileType + "/");//绝对路径
            //string filePath = uploadPath + "\\" + fileType + "\\";  //E:\Fileup  居家
            if (Directory.Exists(filePath) == false) 
            {
                Directory.CreateDirectory(filePath);
            }

            try
            {
                var provider = new ReNameMultipartFormDataStreamProvider(filePath);

                await Request.Content.ReadAsMultipartAsync(provider).ContinueWith(o =>
                {

                    foreach (var file in provider.FileData)
                    {
                        string orfilename = file.Headers.ContentDisposition.FileName.TrimStart('"').TrimEnd('"');//待上传的文件名
                        FileInfo fileinfo = new FileInfo(file.LocalFileName);
                        //判断开始
                        int maxSize = 10000000;
                        string oldName = orfilename;//选择的文件的名称
                        if (fileinfo.Length <= 0)
                        {
                            //文件大小判断 未选择上传的图片 大小为零
                        }
                        else if (fileinfo.Length > maxSize)
                        {
                            //文件大小判断 上传文件是否超限制
                        }
                        else
                        {
                            //
                            string fileExt = orfilename.Substring(orfilename.LastIndexOf('.'));
                            string Extension = fileExt;
                            string CreateTime = DateTime.Now.ToString("yyyyMMddHHmmss");

                            //定义允许上传的文件扩展名 
                            String fileTypes = "gif,jpg,jpeg,png,bmp";
                            if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(fileTypes.Split(','), fileExt.Substring(1).ToLower()) == -1)
                            {

                                returns = "上传的文件格式不是图片";
                            }
                            else
                            {
                                returns = string.Format(@"/Uploads/{0}/{1}", fileType, System.IO.Path.GetFileName(file.LocalFileName));
                            }
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                returns = ex.ToString();
            }
            return returns;
        }

        /// <summary>
        /// 重命名上传的文件
        /// </summary>
        public class ReNameMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
        {
            public ReNameMultipartFormDataStreamProvider(string root)
                : base(root)
            { }

            public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers)
            {

                string extension = !string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName) ? Path.GetExtension(GetValidFileName(headers.ContentDisposition.FileName)) : "";
                return Guid.NewGuid().ToString().Replace("-", "") + extension;
            }

            private string GetValidFileName(string filePath)
            {
                char[] invalids = System.IO.Path.GetInvalidFileNameChars();
                return String.Join("_", filePath.Split(invalids, StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.');
            }

        }
    }
}
View Code

PostMan请求如下:

C# webApi上传图片 代码篇_C# webApi上传图片 代码篇_03

2021-01-07 代码优化如下:

C# webApi上传图片 代码篇_C# webApi上传图片 代码篇_04C# webApi上传图片 代码篇_C# webApi上传图片 代码篇_05
using Iot.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Cors;

namespace Iot.WebSite.Controllers.Apis
{
    [RoutePrefix("api/file")]
    [EnableCors(origins: "*", headers: "*", methods: "GET,POST,PUT,DELETE")]
    public class FileController : ApiController
    {
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<BaseResponse> UploadFileStream()
        {
            var returns = CommonBaseResponse.SetResponse<fileInfoModel>(null, false);
            string fileType = "OTA";//要创建的子文件夹的名字
            var uploadPath = "~/Content";
            string filePath = System.Web.HttpContext.Current.Server.MapPath(uploadPath + "/" + fileType + "/");//绝对路径
            //string filePath = uploadPath + "\\" + fileType + "\\";  //E:\Fileup  居家
            if (Directory.Exists(filePath) == false)
            {
                Directory.CreateDirectory(filePath);
            }
            try
            {
                var provider = new ReNameMultipartFormDataStreamProvider(filePath);
                await Request.Content.ReadAsMultipartAsync(provider).ContinueWith(o =>
                {

                    foreach (var file in provider.FileData)
                    {
                        string orfilename = file.Headers.ContentDisposition.FileName.TrimStart('"').TrimEnd('"');//待上传的文件名
                        FileInfo fileinfo = new FileInfo(file.LocalFileName);
                        //判断开始
                        int maxSize = 1024*1024*100; //小于100M的文件
                        string oldName = orfilename;//选择的文件的名称
                        if (fileinfo.Length <= 0)
                        {
                            returns = CommonBaseResponse.SetResponse<fileInfoModel>(null, false, "未选择上传的附件");
                            //文件大小判断 未选择上传的图片 大小为零
                        }
                        else if (fileinfo.Length > maxSize)
                        {
                            returns = CommonBaseResponse.SetResponse<fileInfoModel>(null, false, "上传文件大小超限制");
                            //文件大小判断 上传文件是否超限制
                        }
                        else
                        {
                            //
                            string fileExt = orfilename.Substring(orfilename.LastIndexOf('.'));
                            string Extension = fileExt;
                            string CreateTime = DateTime.Now.ToString("yyyyMMddHHmmss");

                            //定义允许上传的文件扩展名 
                            String fileTypes = "bin";
                            if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(fileTypes.Split(','), fileExt.Substring(1).ToLower()) == -1)
                            {
                                returns = CommonBaseResponse.SetResponse<fileInfoModel>(null, false, "上传的文件格式不正确");
                            }
                            else
                            {

                                fileInfoModel fileResult = new fileInfoModel()
                                {
                                    oldfilename = oldName,
                                    LocalFilePath = file.LocalFileName,
                                    filesize = fileinfo.Length,
                                    filename= fileinfo.Name,
                                    filepath= uploadPath + "/" + fileType + "/" + fileinfo.Name
                                };

                                var fs = fileinfo.OpenRead();
                                byte[] buffur = new byte[fs.Length];
                                fs.Read(buffur, 0, (int)fs.Length);
                                fileResult.filedata = buffur.ToList();
                                returns = CommonBaseResponse.SetResponse<fileInfoModel>(fileResult, true);
                            }
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("上传附件出错:" + ex.ToString());
            }
            return returns;
        }
    }
    /// <summary>
    /// 重命名上传的文件
    /// </summary>
    public class ReNameMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
    {
        public ReNameMultipartFormDataStreamProvider(string root)
            : base(root)
        { }

        public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers)
        {

            string extension = !string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName) ? Path.GetExtension(GetValidFileName(headers.ContentDisposition.FileName)) : "";
            return Guid.NewGuid().ToString().Replace("-", "") + extension;
        }

        private string GetValidFileName(string filePath)
        {
            char[] invalids = System.IO.Path.GetInvalidFileNameChars();
            return String.Join("_", filePath.Split(invalids, StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.');
        }

    }

    public class fileInfoModel
    {
        /// <summary>
        /// 新文件名称
        /// </summary>
        public string filename { get; set; }
        /// <summary>
        /// 老文件名称
        /// </summary>
        public string oldfilename { get; set; }
        /// <summary>
        /// 服务器绝对地址
        /// </summary>
        public string LocalFilePath { get; set; }
        /// <summary>
        /// 文件大小 字节
        /// </summary>
        public long filesize { get; set; }
        /// <summary>
        /// 问价数据
        /// </summary>
        public List<byte> filedata { get; set; }
        /// <summary>
        /// 文件相对路径
        /// </summary>
        public string filepath { get; set; }
    }
}
View Code

返回值:

C# webApi上传图片 代码篇_C# webApi上传图片 代码篇_06

 

 antd+vue 上传代码

        <a-row align="middle" class="arowLat">
          <a-col :span="12">
            <a-checkable-tag v-model="checked" @change="handleChange">
              OTA固件包
            </a-checkable-tag>
            <a-upload
              action="http://xxxxxxxx.com/api/File/UploadFileStream"
            >
              <a-button> <a-icon type="upload" /> 选择升级固件 </a-button>
            </a-upload>
          </a-col>
          <a-col :span="12"> </a-col>
        </a-row>