一个.net6简单的图片上传(文件也可用)

#一个.net6简单的图片上传(文件也可用)
##页面

@{ViewData["Title"] = "图片上传Demo";
}
图片上传:

##后端(控制器)

using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using UploadDemo.Models;
using System.Web;namespace UploadDemo.Controllers
{public class HomeController : Controller{private readonly ILogger _logger;public HomeController(ILogger logger){_logger = logger;}public IActionResult Index(){return View();}[HttpPost]public async Task FileSave(){//获取Form提交的文件var file = Request.Form.Files["file"];if (file != null){if (file.Length > 0){int count = file.FileName.Split('.').Length;//统计.将名字分为几个部分string exp = file.FileName.Split('.')[count - 1];//最后一部分为后缀名Console.WriteLine("文件名:{0}\n文件扩展名:{1}", file.FileName, exp);string filePath = "D:/desktop/test/";//保存目录不存在就创建这个目录if (!Directory.Exists(filePath)){Directory.CreateDirectory(filePath);}//在指定目录创建文件string fileName = filePath + "上传测试" + ".jpg";//文件名FileHelper.CreateFile(fileName);using (var stream = new FileStream(fileName, FileMode.Create)){await file.CopyToAsync(stream);}}}return RedirectToAction(nameof(Index));}public IActionResult Privacy(){return View();}[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]public IActionResult Error(){return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });}}
}

##辅助类:

namespace UploadDemo
{public static class FileHelper{/// /// 拷贝文件/// /// 源文件路径/// 目标文件的路径/// public static void FileCoppy(string orignFile, string newFile){if (string.IsNullOrEmpty(orignFile)){throw new ArgumentException(orignFile);}if (string.IsNullOrEmpty(newFile)){throw new ArgumentException(newFile);}System.IO.File.Copy(orignFile, newFile, true);}/// /// 删除文件/// /// 要删除的文件的路径/// public static void FileDel(string path){if (string.IsNullOrEmpty(path)){throw new ArgumentException(path);}System.IO.File.Delete(path);}/// /// 移动文件/// /// 原始路径/// 新路径/// public static void FileMove(string orignFile, string newFile){if (string.IsNullOrEmpty(orignFile)){throw new ArgumentException(orignFile);}if (string.IsNullOrEmpty(newFile)){throw new ArgumentException(newFile);}System.IO.File.Move(orignFile, newFile);}/// /// 创建路径/// /// 路径public static void CreatePath(string FilePath){if (!Directory.Exists(FilePath)){Directory.CreateDirectory(FilePath);}}/// /// 创建文件/// /// public static void CreateFile(string FilePath){if (!File.Exists(FilePath)){FileStream fs = File.Create(FilePath);fs.Close();}}}
}


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部