ASP. NET example of uploading files to a shared folder

  • 2021-11-29 06:44:13
  • OfStack

Directory upload file code web. config tool method constant specific upload file code

Creating Shared Folder Resources

Upload file code

web. config


    <!-- Upload file configuration ,UploadPath Value 1 It must be the server ip Intranet ip Best -->
    <add key="UploadPath" value="\\172.21.0.10\File" />
    <add key="DownloadPath" value="http://x.x.x.x:80/" />
    <add key="UserName" value="ShareUser" />
    <add key="Password" value="P@ssw0rd" />

Tool method


public static string GetConfigString(string key, string @default = "")
        {
            return ConfigurationManager.AppSettings[key] ?? @default;
        }

    /// <summary>
    ///  Get the folder name to save according to the file name (including file extension) 
    /// </summary>
    public class FileHelper
    {
        /// <summary>
        ///  Get the folder name to save according to the file name (including file extension) 
        /// </summary>
        /// <param name="fileName"> File name (including file extension) </param>
        public static string GetSaveFolder(string fileName)
        {
            var fs = fileName.Split('.');
            var ext = fs[fs.Length - 1];
            var str = string.Empty;
            var t = ext.ToLower();
            switch (t)
            {
                case "jpg":
                case "jpeg":
                case "png":
                case "gif":
                    str = "images";
                    break;
                case "mp4":
                case "mkv":
                case "rmvb":
                    str = "video";
                    break;
                case "apk":
                case "wgt":
                    str = "app";
                    break;
                case "ppt":
                case "pptx":
                case "doc":
                case "docx":
                case "xls":
                case "xlsx":
                case "pdf":
                    str = "file";
                    break;
                default:
                    str = "file";
                    break;
            }

            return str;
        }
    }

    /// <summary>
    ///  Logging helper class 
    /// </summary>
    public class WriteHelper
    {
        public static void WriteFile(object data)
        {
            try
            {
                string path = $@"C:\Log\";
                var filename = $"Log.txt";
                if (!Directory.Exists(path))
                    Directory.CreateDirectory(path);
                TextWriter tw = new StreamWriter(Path.Combine(path, filename), true); //true Add data at the end of the file 

                tw.WriteLine($"---- Generation time: {DateTime.Now:yyyy-MM-dd HH:mm:ss}---------------------------------------------------------------------");

                tw.WriteLine(data.ToJson());
                tw.Close();
            }
            catch (Exception e)
            {

            }
        }
    }

Constant


/// <summary>
    ///  File upload configuration item 
    /// </summary>
    public class FileUploadConst
    {
        /// <summary>
        ///  Upload address 
        /// </summary>
        public static string UploadPath => ConfigHelper.GetConfigString("UploadPath");

        /// <summary>
        ///  File access / Download address 
        /// </summary>
        public static string DownloadPath => ConfigHelper.GetConfigString("DownloadPath");

        /// <summary>
        ///  Access shared directory user name 
        /// </summary>
        public static string UserName => ConfigHelper.GetConfigString("UserName");

        /// <summary>
        ///  Access shared directory password 
        /// </summary>
        public static string Password => ConfigHelper.GetConfigString("Password");
    }

Specific upload file code


/// <summary>
        ///  Upload files to shared folders 
        /// </summary>
        [HttpPost, Route("api/Upload/UploadAttachment")]
        [AllowAnonymous]
        public ServiceResponse<UploadRespModel> UploadAttachment()
        {
            var viewModel = new UploadRespModel();
            var code = 200;
            var msg = " Upload failed !";

            var path = FileUploadConst.UploadPath; //@"\\172.16.10.130\Resource";
            var s = connectState(path, FileUploadConst.UserName, FileUploadConst.Password);

            if (s)
            {
                var filelist = HttpContext.Current.Request.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}";

                    // Directory of shared folders 
                    var theFolder = new DirectoryInfo(path);
                    var remotePath = theFolder.ToString();
                    Transport(file.InputStream, remotePath, fileName);

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

                    msg = " Upload succeeded ";
                }
            }
            else
            {
                code = CommonConst.Code_OprateError;
                msg = " Linked Server Failure ";
            }

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

        /// <summary>
        ///  Connect to a remote shared folder 
        /// </summary>
        /// <param name="path"> The path to the remote shared folder </param>
        /// <param name="userName"> User name </param>
        /// <param name="passWord"> Password </param>
        private static bool connectState(string path, string userName, string passWord)
        {
            bool Flag = false;
            Process 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();
                string dosLine = "net use " + path + " " + passWord + " /user:" + userName;
                WriteHelper.WriteFile($"dosLine:{dosLine}");
                proc.StandardInput.WriteLine(dosLine);
                proc.StandardInput.WriteLine("exit");
                while (!proc.HasExited)
                {
                    proc.WaitForExit(1000);
                }

                string errormsg = proc.StandardError.ReadToEnd();
                proc.StandardError.Close();
                WriteHelper.WriteFile($"errormsg:{errormsg}");
                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;
        }

        /// <summary>
        ///  Save local content to a remote folder, or download files from a remote folder to the local 
        /// </summary>
        /// <param name="inFileStream"> The path of the file to be saved. If the file is saved to a shared folder, this path is the local file path such as: @"D:\1.avi"</param>
        /// <param name="dst"> Path to save the file, without name and extension </param>
        /// <param name="fileName"> Save the name and extension of the file </param>
        private static void Transport(Stream inFileStream, string dst, string fileName)
        {
            WriteHelper.WriteFile($" Directory -Transport : {dst}");
            if (!Directory.Exists(dst))
            {
                Directory.CreateDirectory(dst);
            }

            dst = dst + fileName;

            if (!File.Exists(dst))
            {
                WriteHelper.WriteFile($" File does not exist, start saving ");
                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);
                }
                WriteHelper.WriteFile($" Save complete ");
                inFileStream.Flush();

                inFileStream.Close();

                outFileStream.Flush();

                outFileStream.Close();
            }
        }

These are the details of ASP. NET uploading files to a shared folder. For more information about ASP. NET uploading files, please pay attention to other related articles on this site!


Related articles: