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

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

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

<form asp-action="FileSave" enctype="multipart/form-data">
    图片上传: <input type="file" name="file" value="选择" />
               <input type="submit"value="上传"/>
</form>

##后端(控制器)

using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using UploadDemo.Models;
using System.Web;

namespace UploadDemo.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> 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
    {
        /// <summary>
        /// 拷贝文件
        /// </summary>
        /// <param name="orignFile">源文件路径</param>
        /// <param name="newFile">目标文件的路径</param>
        /// <exception cref="ArgumentException"></exception>
        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);
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="path">要删除的文件的路径</param>
        /// <exception cref="ArgumentException"></exception>
        public static void FileDel(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentException(path);
            }
            System.IO.File.Delete(path);
        }

        /// <summary>
        /// 移动文件
        /// </summary>
        /// <param name="orignFile">原始路径</param>
        /// <param name="newFile">新路径</param>
        /// <exception cref="ArgumentException"></exception>
        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);
        }

        /// <summary>
        /// 创建路径
        /// </summary>
        /// <param name="FilePath">路径</param>
        public static void CreatePath(string FilePath)
        {
            if (!Directory.Exists(FilePath))
            {
                Directory.CreateDirectory(FilePath);
            }
        }

        /// <summary>
        /// 创建文件
        /// </summary>
        /// <param name="FilePath"></param>
        public static void CreateFile(string FilePath)
        {
            if (!File.Exists(FilePath))
            {
                FileStream fs = File.Create(FilePath);
                fs.Close();
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值