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

2021-03-03 11:25

阅读:518

标签:datetime   rms   text   sha   链接   void   方法   远程文件   lex   

参考资料: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 新建实体类  

 

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

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

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

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

2.2  映射实体类与配置项

在startup.cs中配置    

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

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

 

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

二、上传文件

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

1.连接文件服务器方法 

        /// 
        /// 连接远程共享文件夹
        /// 
        /// 远程共享文件夹的路径
        /// 用户名
        /// 密码
        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.传输文件流到服务器中

        /// 
        /// 向远程文件夹保存本地内容,或者从远程文件夹下载文件到本地
        /// 
        /// 要保存的文件的路径,如果保存文件到共享文件夹,这个路径就是本地文件路径如:@"D:\1.avi"
        /// 保存文件的路径,不含名称及扩展名
        /// 保存文件的名称以及扩展名
        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.接收文件并上传到文件服务器

        /// 
        /// 上传附件到文件服务器中
        /// 
        [HttpPost, Route("api/Upload/UploadAttachment")]
        [AllowAnonymous]
        public ServiceResponse 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.SuccessResponse(msg, viewModel, code);
        }

 4.图片地址拼接方法

        /// 
        /// 拼接文件全路径
        /// 
        /// 文件相对地址
        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;
        }

 

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

标签:datetime   rms   text   sha   链接   void   方法   远程文件   lex   

原文地址:https://www.cnblogs.com/dawenyang/p/14269461.html


评论


亲,登录后才可以留言!