ASP.NET Core 上传文件到共享文件夹

人生苦短我用Python,本文助你快速入门

参考资料:ASP.NET 上传文件到共享文件夹

创建共享文件夹参考资料:https://www.cnblogs.com/dansediao/p/5712657.html

一、配置上传文件相关参数并读取参数

1.配置appsettings.json    

{
    "FileUploadInfo": {
    "UploadPath": "\\\\172.21.0.10\\File",
    "DownloadPath": "http://213.10.11.126:8001/",
    "UserName": "ShareUser",
    "Password": "Password"
    }  
}

2.读取配置数据

2.1 新建实体类  

 

.NET 云原生架构师训练营(模块二 基础巩固 RabbitMQ Masstransit 介绍)–学习笔记

    /// <summary>
    /// 文件上传配置项
    /// </summary>
    public class FileUploadConst
    {
        /// <summary>
        /// 上传地址
        /// </summary>
        public string UploadPath { get; set; }

        /// <summary>
        /// 文件访问/下载地址
        /// </summary>
        public string DownloadPath { get; set; }

        /// <summary>
        /// 访问共享目录用户名
        /// </summary>
        public string UserName { get; set; }

        /// <summary>
        /// 访问共享目录密码
        /// </summary>
        public string Password { get; set; }
    }

2.2  映射实体类与配置项

在startup.cs中配置    

                public void ConfigureServices(IServiceCollection services) { services.Configure<FileUploadConst>(Configuration.GetSection("FileUploadInfo")); }

3.控制器中读取配置项,通过注入的方式

 

        public FileUploadConst FileUploadConfig { get; set; }
        public UploadController(IOptions<FileUploadConst> option)
        {
            FileUploadConfig = option.Value;
        }

二、上传文件

  上传文件之前记得初始化构造方法,注入文件上传配置项!!!!!↑

1.连接文件服务器方法 

        /// <summary>
        /// 连接远程共享文件夹
        /// </summary>
        /// <param name="path">远程共享文件夹的路径</param>
        /// <param name="userName">用户名</param>
        /// <param name="passWord">密码</param>
        private static bool connectState(string path, string userName, string passWord)
        {
            var flag = false;
            var proc = new Process();
            try
            {
                proc.StartInfo.FileName = "cmd.exe";
                proc.StartInfo.UseShellExecute = false;
                proc.StartInfo.RedirectStandardInput = true;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.RedirectStandardError = true;
                proc.StartInfo.CreateNoWindow = true;
                proc.Start();
                var dosLine = "net use " + path + " " + passWord + " /user:" + userName;
                proc.StandardInput.WriteLine(dosLine);
                proc.StandardInput.WriteLine("exit");
                while (!proc.HasExited)
                {
                    proc.WaitForExit(1000);
                }

                var errormsg = proc.StandardError.ReadToEnd();
                proc.StandardError.Close();if (string.IsNullOrEmpty(errormsg))
                {
                    flag = true;
                }
                else
                {
                    throw new Exception(errormsg);
                }
            }
            catch (Exception ex)
            {
                WriteHelper.WriteFile(ex);
                throw ex;
            }
            finally
            {
                proc.Close();
                proc.Dispose();
            }

            return flag;
        } 

2.传输文件流到服务器中

        /// <summary>
        /// 向远程文件夹保存本地内容,或者从远程文件夹下载文件到本地
        /// </summary>
        /// <param name="inFileStream">要保存的文件的路径,如果保存文件到共享文件夹,这个路径就是本地文件路径如:@"D:\1.avi"</param>
        /// <param name="dst">保存文件的路径,不含名称及扩展名</param>
        /// <param name="fileName">保存文件的名称以及扩展名</param>
        private static void Transport(Stream inFileStream, string dst, string fileName)
        {if (!Directory.Exists(dst))
            {
                Directory.CreateDirectory(dst);
            }

            dst = dst + fileName;

            if (!System.IO.File.Exists(dst))
            {var outFileStream = new FileStream(dst, FileMode.Create, FileAccess.Write);

                var buf = new byte[inFileStream.Length];

                int byteCount;

                while ((byteCount = inFileStream.Read(buf, 0, buf.Length)) > 0)
                {
                    outFileStream.Write(buf, 0, byteCount);
                }
                inFileStream.Flush();

                inFileStream.Close();

                outFileStream.Flush();

                outFileStream.Close();
            }
        }

3.接收文件并上传到文件服务器

        /// <summary>
        /// 上传附件到文件服务器中
        /// </summary>
        [HttpPost, Route("api/Upload/UploadAttachment")]
        [AllowAnonymous]
        public ServiceResponse<UploadRespModel> UploadAttachment()
        {
            var viewModel = new UploadRespModel();
            var code = 200;
            var msg = "上传失败!";

            var path = FileUploadConfig.UploadPath; //@"\\172.16.10.130\Resource";
            var s = connectState(path, FileUploadConfig.UserName, FileUploadConfig.Password);
            try
            {
                if (s)
                {
                    var filelist = HttpContext.Request.Form.Files;
                    if (filelist.Count > 0)
                    {
                        var file = filelist[0];
                        var fileName = file.FileName;
                        var blobName = FileHelper.GetSaveFolder(fileName);
                        path = $@"{path}\{blobName}\";

                        fileName = $"{DateTime.Now:yyyyMMddHHmmss}{fileName}";

                        //共享文件夹的目录
                        var theFolder = new DirectoryInfo(path);
                        var remotePath = theFolder.ToString();
                        Transport(file.OpenReadStream(), remotePath, fileName);

                        viewModel.SaveUrl = $"{blobName}/{fileName}";
                        viewModel.DownloadUrl = GetFileFullPath(viewModel.SaveUrl);

                        msg = "上传成功";
                    }
                }
                else
                {
                    code = CommonConst.Code_OprateError;
                    msg = "链接服务器失败";
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                msg = e.Message;
            }

            return ServiceResponse<UploadRespModel>.SuccessResponse(msg, viewModel, code);
        }

 4.图片地址拼接方法

        /// <summary>
        /// 拼接文件全路径
        /// </summary>
        /// <param name="filePath">文件相对地址</param>
        private string GetFileFullPath(string filePath)
        {
            var str = string.Empty;
            if (!string.IsNullOrEmpty(filePath))
            {
                // 兼容旧数据
                if (filePath.Contains("http://") || filePath.Contains("https://"))
                {
                    str = filePath;
                }
                else
                {
                    var host = FileUploadConfig.DownloadPath;
                    str = $"{host}/{filePath}";
                }
            }
            return str;
        }

 

ThreadX应用笔记:内核初始化和任务调度

除非注明,否则均为醉墨淋漓 | 精品互联网资源原创文章,转载必须以链接形式标明本文链接

本文链接:https://momeis.net/post-3213.html

给TA买糖
共{{data.count}}人
人已赞赏
经验教程

Java安全之Weblogic 2016-3510 分析

2021-1-12 21:43:00

经验教程

ThreadX应用笔记:内核初始化和任务调度

2021-1-12 22:01:00

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
今日签到
有新私信 私信列表
搜索