首页 > Windows开发 > 详细

c# http文件上传

时间:2019-04-22 11:52:37      阅读:140      评论:0      收藏:0      [点我收藏+]
        /// <summary>
        /// 上传文件的api
        /// </summary>
        [HttpPost]
        public string UploadFile(op_client_billfile_info model)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + "BillFile";
            path += model.path;
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);
            model.filename = ExistFile(path, model.filename.Replace(" ", ""));

            MemoryStream ms = new MemoryStream(model.by);
            FileStream fs = new FileStream(path + "\\" + model.filename, FileMode.OpenOrCreate);
            ms.WriteTo(fs);
            ms.Close();
            fs.Close();
            return model.filename;
        }
        /// <summary>
        /// 文件名重复加(1)
        /// </summary>
        [NonAction]
        private string ExistFile(string path, string filename)
        {
            int count = 1;
            //在重复名称后加(序号)
            while (File.Exists(path + "\\" + filename))
            {
                if (filename.Contains(")."))
                {
                    int start = filename.LastIndexOf("(");
                    int end = filename.LastIndexOf(").") - filename.LastIndexOf("(") + 2;
                    filename = filename.Replace(filename.Substring(start, end), string.Format("({0}).", count));
                }
                else
                {
                    filename = filename.Replace(".", string.Format("({0}).", count));
                }
                count++;
            }
            return filename;
        }

上传文件类

        /// <summary>
        /// 账单文件信息的id
        /// </summary>        
        public int bid { get; set; }
        /// <summary>
        /// 文件名
        /// </summary>        
        public string filename { get; set; }
        /// <summary>
        /// 放在服务器的路径
        /// </summary>        
        public string path { get; set; }
        /// <summary>
        /// 文件
        /// </summary>
        public byte[] by { get; set; }

下载文件

        /// <summary>
        /// 保存文件
/// url 文件地址(iis);path 保存地址;fileName 保存文件名
/// </summary> private void DownloadFile(string url, string path, string fileName) { Stream sm = WebRequest.Create(url).GetResponse().GetResponseStream(); FileStream fs = new FileStream(path + "\\" + fileName, FileMode.OpenOrCreate); sm.CopyTo(fs); sm.Close(); fs.Close(); }

 post请求封装地址:https://www.cnblogs.com/shuaimeng/p/9871582.html

 

c# http文件上传

原文:https://www.cnblogs.com/shuaimeng/p/10749212.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!