京东6.18大促主会场领京享红包更优惠

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 8057|回复: 0

ASP.NET 上传文件到共享文件夹的示例

[复制链接]

23

主题

0

回帖

10

积分

新手上路

积分
10
发表于 2021-7-25 20:50:18 | 显示全部楼层 |阅读模式 来自 中国
目录
2 B9 H( \( s/ a) b2 M9 q. h' o/ G- ^3 {9 N7 S
    / J' k& t6 B$ _, h" s
  • 上传文件代码7 o1 J7 ~- V% B7 j4 _6 V

      1 I+ B- I  J$ f0 b# C7 x
    •   web.config & Z- t* L7 r2 F1 @& C
    •   工具方法  
      1 B: f9 e# L% n# F' K
    •   常量
      $ `+ u5 |. b' _- a8 d' Z
    •   具体上传文件代码
      * a' g7 @# ?3 p9 c/ v9 C
    , e% V+ m6 w& `6 c
创建共享文件夹参考资料
0 t- y8 G6 ?( N3 ~. T/ c. g
- @7 ^+ b2 L( w- C# K% [上传文件代码
* U* |8 u% ?6 w5 \' g5 g, L% q' [; X

- B& H2 I2 ]- f1 N  F& t7 R1 b4 M- @. w6 u6 H$ `2 Z9 ]( ?) Z5 P: L! `
1 O" u' z9 R! |3 Z
  web.config ; K. b3 [1 D- O/ ^% c
  1.                
复制代码
  工具方法  
& k/ j4 O/ T+ s+ I1 P7 ]' E! Z
  1. public static string GetConfigString(string key, string @default = "")        {            return ConfigurationManager.AppSettings[key] ?? @default;        }    ///     /// 根据文件名(包含文件扩展名)获取要保存的文件夹名称    ///     public class FileHelper    {        ///         /// 根据文件名(包含文件扩展名)获取要保存的文件夹名称        ///         /// 文件名(包含文件扩展名)        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;        }    }    ///     /// 记录日志帮助类    ///     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在文件末尾添加数据                tw.WriteLine($"----产生时间:{DateTime.Now:yyyy-MM-dd HH:mm:ss}---------------------------------------------------------------------");                tw.WriteLine(data.ToJson());                tw.Close();            }            catch (Exception e)            {            }        }    }
复制代码
  常量6 P* ^: T% T( _. p
  1. ///     /// 文件上传配置项    ///     public class FileUploadConst    {        ///         /// 上传地址        ///         public static string UploadPath => ConfigHelper.GetConfigString("UploadPath");        ///         /// 文件访问/下载地址        ///         public static string DownloadPath => ConfigHelper.GetConfigString("DownloadPath");        ///         /// 访问共享目录用户名        ///         public static string UserName => ConfigHelper.GetConfigString("UserName");        ///         /// 访问共享目录密码        ///         public static string Password => ConfigHelper.GetConfigString("Password");    }
复制代码
  具体上传文件代码4 n* I7 \+ M) U2 D7 t9 }
  1. ///         /// 上传文件到共享文件夹        ///         [HttpPost, Route("api/Upload/UploadAttachment")]        [AllowAnonymous]        public ServiceResponse UploadAttachment()        {            var viewModel = new UploadRespModel();            var code = 200;            var msg = "上传失败!";            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}";                    //共享文件夹的目录                    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 = "上传成功";                }            }            else            {                code = CommonConst.Code_OprateError;                msg = "链接服务器失败";            }            return ServiceResponse.SuccessResponse(msg, viewModel, code);        }        ///         /// 连接远程共享文件夹        ///         /// 远程共享文件夹的路径        /// 用户名        /// 密码        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;        }        ///         /// 向远程文件夹保存本地内容,或者从远程文件夹下载文件到本地        ///         /// 要保存的文件的路径,如果保存文件到共享文件夹,这个路径就是本地文件路径如:@"D:\1.avi"        /// 保存文件的路径,不含名称及扩展名        /// 保存文件的名称以及扩展名        private static void Transport(Stream inFileStream, string dst, string fileName)        {            WriteHelper.WriteFile($"目录-Transport:{dst}");            if (!Directory.Exists(dst))            {                Directory.CreateDirectory(dst);            }            dst = dst + fileName;            if (!File.Exists(dst))            {                WriteHelper.WriteFile($"文件不存在,开始保存");                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($"保存完成");                inFileStream.Flush();                inFileStream.Close();                outFileStream.Flush();                outFileStream.Close();            }        }
复制代码
以上就是ASP.NET 上传文件到共享文件夹的示例的详细内容,更多关于ASP.NET 上传文件的资料请关注脚本之家其它相关文章!
  ~, N: q8 [8 t& f
" x. \$ T% `; J9 B) Z0 N/ k- b来源:http://www.jb51.net/article/209483.htm' f9 ^0 M. N3 y7 P2 \& P# M5 P. ]
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

帖子地址: 

梦想之都-俊月星空 优酷自频道欢迎您 http://i.youku.com/zhaojun917
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|手机版|小黑屋|梦想之都-俊月星空 ( 粤ICP备18056059号 )|网站地图

GMT+8, 2026-3-20 11:07 , Processed in 0.035846 second(s), 23 queries .

Powered by Mxzdjyxk! X3.5

© 2001-2026 Discuz! Team.

快速回复 返回顶部 返回列表