惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

罗磊的独立博客
L
LangChain Blog
aimingoo的专栏
aimingoo的专栏
IT之家
IT之家
B
Blog
博客园_首页
博客园 - 司徒正美
有赞技术团队
有赞技术团队
博客园 - 聂微东
I
InfoQ
美团技术团队
GbyAI
GbyAI
阮一峰的网络日志
阮一峰的网络日志
H
Help Net Security
大猫的无限游戏
大猫的无限游戏
MyScale Blog
MyScale Blog
WordPress大学
WordPress大学
The GitHub Blog
The GitHub Blog
A
About on SuperTechFans
人人都是产品经理
人人都是产品经理
Microsoft Azure Blog
Microsoft Azure Blog
Engineering at Meta
Engineering at Meta
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
The Cloudflare Blog

博客园 - Insus.NET

Vue3实现拖放式上传 拖放式上传 文件上传和表单字段混合提交 在HttpContext.Current返回null时如何操作 angularjs根据类型动态加载组件 angularjs获取数据服务 扫一扫直连WiFi二维码 User Profile Service 服务未能登录 Visual Studio2026创建Vue项目 安装与配置node.js HTTP Error 403.14 - Forbidden VisualStudio2026回滚上一版本 消息认证码(加强) 网站无法使用插值字符串语法 HMAC(Hash-based Message Authentication Code)认证示例 浏览器自动发送域凭据 企业内小网站兼用Windows验证登录 访问用户控件的函数 onblur事件改为监听处理 将警报消息改为吐司消息 内容有无变化OnBlur即时更新引起的问题与解决 混合式提高用户编辑与操作效率 光标离开文框后即刻更新 WebForm实现Web API JavaScript对GridView删除行后并重新给其数据绑定 把CS值传给JS使用 v2 确认信息confirm由C#后端移至javascript前端 无法发布网站Web Site JavaScript判断字符是否为decimal 点击单元格弹出窗口处理数据返回父页
实现MultipartStreamProvider经Web API上传文档或图片
Insus.NET · 2026-09-13 · via 博客园 - Insus.NET

从这里,我们慢慢跟着它一步一步实现自己的上传功能,先从简单入手。

<div>
    <input id="FileImage" type="file" />
    <input id="BtnUpload" type="button" value="上传" />
</div>

运行起来,效果:
2026-09-13_09-45-07

重点部分,即是创建Web API,把用户上传的文档图片存储起来,数据库,文件夹等。

2026-09-13_10-18-03

2026-09-13_10-29-57

namespace Insus.NET.Models
{
    public class Response
    {
        public bool Status { get; set; }
        public string Message { get; set; }
        public object Data { get; set; }

        public Response() { }

        public Response(bool status, string message, object data)
        {
            Status = status;
            Message = message;
            Data = data;
        }
    }
}

Response

public async Task<IHttpActionResult> UploadImage()
{
    Response _Data;  //Model
    try
    {
        await ProcessPostImageFile();

        _Data = new Response()
        {
            Status = true,
            Message = "File uploaded successfully.",
            Data = null
        };
    }
    catch (Exception ex)
    {
        _Data = new Response()
        {
            Status = false,
            Message = ex.Message,
            Data = null
        };
    }
    return Ok(_Data);
}

UploadImage()

 private async Task ProcessPostImageFile()
 {
     if (!Request.Content.IsMimeMultipartContent())
     {
         throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
     }

     var provider = await Request.Content.ReadAsMultipartAsync<InsusNetMultipartFormDataStreamProvider>(
         new InsusNetMultipartFormDataStreamProvider()
     );

     NameValueCollection formData = provider.FormData;
     IList<HttpContent> files = provider.Files;


     foreach (var file in files)
     {
         var _ocr = new OcrFile();

         string ofn = file.Headers.ContentDisposition.FileName.Trim('"'); //去掉前后的引号
         _ocr.OriginalFileName = ofn; //上传的文件名
         _ocr.Extension = Path.GetExtension(ofn);  //扩展名
         _ocr.MimeType = file.Headers.ContentType.MediaType;  //图片文档的Media type。

         using (var ms = new MemoryStream())  //不管你是上传单文件,还是上传多文件,均需从内存流去读取数据。
         {
             var stream = await file.ReadAsStreamAsync();
             await stream.CopyToAsync(ms);

             _ocr.Size = ms.Length;
             ms.Position = 0; // 重置位置供后续使用
             using (var image = Image.FromStream(ms))
             {
                 System.Drawing.Imaging.ImageFormat format = ImageUtil.GetImageFormat(image);  //这里自定义方法,从图片获取其格式。
                 string extension = ImageUtil.GetExtensionByImageFormat(format);  //这里也是自定义方法,从图片格式获取其扩展名

                 string newFileName = $"{Guid.NewGuid()}{extension}"; //用GUID生成唯一文件名
                 _ocr.NewFileName = newFileName;

                 string newFileFullPath = Path.Combine(InsusIO.TempDirectory, newFileName);
                 image.Save(newFileFullPath, format); //存储入文件夹中。
             }
         }

         await Task.Run(() => xxx.Save2Db(_ocr)); //相关数据存入数据库中
     }
 }

ProcessPostImageFile()


2026-09-13_10-41-41

namespace Insus.NET
{
    public static class ImageUtil
    {
        public static ImageFormat GetImageFormat(Image image)
        {
            if (image.RawFormat.Equals(ImageFormat.Jpeg))
                return ImageFormat.Jpeg;           
            else if (image.RawFormat.Equals(ImageFormat.Png))
                return ImageFormat.Png;
            else if (image.RawFormat.Equals(ImageFormat.Tiff))
                return ImageFormat.Tiff;
            else if (image.RawFormat.Equals(ImageFormat.Gif))
                return ImageFormat.Gif;
            else if (image.RawFormat.Equals(ImageFormat.Bmp))
                return ImageFormat.Bmp;
            else if (image.RawFormat.Equals(ImageFormat.Emf))
                return ImageFormat.Emf;
            else if (image.RawFormat.Equals(ImageFormat.Exif))
                return ImageFormat.Exif;
            else if (image.RawFormat.Equals(ImageFormat.Icon))
                return ImageFormat.Icon;
            else if (image.RawFormat.Equals(ImageFormat.Wmf))
                return ImageFormat.Wmf;
            else
                return ImageFormat.Jpeg; // 默认使用JPEG
        }

        public static string GetExtensionByImageFormat(ImageFormat format)
        {
            if (format.Equals(ImageFormat.Jpeg)) return ".jpg";
            if (format.Equals(ImageFormat.Png)) return ".png";
            if (format.Equals(ImageFormat.Tiff)) return ".tiff";
            if (format.Equals(ImageFormat.Gif)) return ".gif";
            if (format.Equals(ImageFormat.Bmp)) return ".bmp";
            if (format.Equals(ImageFormat.Icon)) return ".ico";
            // 其他格式...
            return ".jpg"; // 默认
        }
    }
}

ImageUtil

前端javascript,调用Web API。
2026-09-13_10-49-45


上面代码中,还是一行#59,

var _ocr = new OcrFile();

即是图片相关属性model。

本篇简单的图片上传。细看代码,没有什么困难之处。初学者入门篇。