老K博客 - 一个源码和技术分享的博客

C# .NET MVC实现图片、视频上传接口

老K博客
2025-01-11 / 0 评论 / 22 阅读 / 正在检测是否收录...
广告

我们经常会上传图片或者视频,介绍一下用.NET MVC实现图片、视频上传接口的三种方式

一、 Base64图片上传

适合小程序端

/// </summary>
/// <param name="base64String"></param>
/// <param name="filePath"></param>
/// <param name="fileName"></param>
/// <returns></returns>
public static string UpLoadImage(string base64String)
{    
  FileStream fs = null;    
  BinaryWriter bw = null;    
  try    
  {        
    if (string.IsNullOrEmpty(base64String))        
                                                                                                             {            
                                                                                                               throw new Exception("图片参数不能为空");        
                                                                                                             }        
    string filePath = "/UpLoad/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day;
    string realPath = HttpContext.Current.Server.MapPath("~/" + filePath);
    string day = YearMonthDay;
    if (!Directory.Exists(realPath))//如果不存在就创建file文件夹
    {
      Directory.CreateDirectory(realPath);
    }
        string imagePath = filePath + "/" + fileName;
    string imageSavePath = realPath + "/" + fileName;
    byte[] arr = Convert.FromBase64String(base64String);
    fs = new System.IO.FileStream(imageSavePath, System.IO.FileMode.Create);
    bw = new System.IO.BinaryWriter(fs);        bw.Write(arr);
    bw.Close();
    fs.Close();
    
        return imagePath;
  }
  catch (Exception ex)
  {
        
    if (bw != null)
    {
      bw.Close();
      }
      if (fs != null)
      {
        fs.Close();
        }
        throw new Exception(ex.Message);
      }
    }

二、HttpPostedFile文件上传

适合网页端

/// <summary>/// 上传图片、视频 HttpPostedFile/// </summary>/// <returns></returns>[HttpPost]public ApiResponse UploadPostFile(){    try    {        string filePath = "/UpLoad/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day;        string realPath = HttpContext.Current.Server.MapPath("~/" + filePath);        if (!Directory.Exists(realPath))//如果不存在就创建file文件夹        {            Directory.CreateDirectory(realPath);        }
        HttpPostedFile file = HttpContext.Current.Request.Files[0];        string fileType = HttpContext.Current.Request.Form["fileType"];
        string imagePath = filePath + "/" + "test.jpg";
        file.SaveAs(imagePath);
        return imagePath;    }    catch (Exception e)    {        return BaseApiResponse.ApiError(e.Message);    }}

三、FormData上传(通过表单(multipart/form-data)的方式上传后)

安装MultipartDataMediaFormatter
m5s9kfxq.png

路由配置

m5s9kqq7.png

配置代码

//为了实现通过实体类获取文件
GlobalConfiguration.Configuration.Formatters.Add(new FormMultipartEncodedMediaTypeFormatter());

file和表单一起

/// <param name="formData"></param>/// <returns></returns>[HttpPost]public string UploadFormData(FormData formData){    try    {        string filePath = "/UpLoad/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day;
        string realPath = HttpContext.Current.Server.MapPath("~/" + filePath);        if (!Directory.Exists(realPath))//如果不存在就创建file文件夹        {            Directory.CreateDirectory(realPath);        }
        string fileType = formData.Fields[0].Value;
        string imagePath = filePath + "/" + "test.jpg";
        FileStream fs = null;        BinaryWriter bw = null;        byte[] arr = formData.Files[0].Value.Buffer;        fs = new System.IO.FileStream(imagePath, System.IO.FileMode.Create);        bw = new System.IO.BinaryWriter(fs);        bw.Write(arr);        bw.Close();        fs.Close();
        return imagePath;    }    catch (Exception e)    {        throw new Exception(ex.Message);    }}

四、用Postman测试一下吧

m5s9m20x.png
成功接收到图片
m5s9m7zv.png

本文共 156 个字数,平均阅读时长 ≈ 1分钟
广告
0

海报

正在生成.....

评论 (0)

语录
取消
CC BY-NC-ND