在程序開發(fā)項(xiàng)目中我們經(jīng)常會上傳圖片或者視頻,下面介紹一下用.NET MVC實(shí)現(xiàn)圖片、視頻上傳接口的三種方式;有興趣的小伙伴們可以一起學(xué)習(xí)。
一、 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("圖片參數(shù)不能為空");
}
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))//如果不存在就創(chuàng)建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文件上傳
適合網(wǎng)頁端
/// <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))//如果不存在就創(chuàng)建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
?
路由配置
配置代碼
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))//如果不存在就創(chuàng)建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測試一下吧
成功接收到圖片
該文章在 2025/1/3 16:54:23 編輯過