您的位置:首页 > 其它

.net 用file上传文件到服务器方法

2017-02-15 10:26 309 查看
 后台

public  void Btn_click(){

   HttpFileCollection files = HttpContext.Current.Request.Files;

        HttpPostedFile postFile = files["Filetype"];

        string fileName = Path.GetFileName(postFile.FileName);

        string path = SaveFiles(fileName, "Filetype");

}

private string SaveFiles(string FileName,string iFile)

    {

        string imgPathPart = "";

        ///'遍历File表单元素

        HttpFileCollection files = HttpContext.Current.Request.Files;

        try

        {

            ///'检查文件扩展名字

            HttpPostedFile postedFile = files[iFile];

            string fileName;

            fileName = System.IO.Path.GetFileName(postedFile.FileName);

            if (fileName != "")

            {

                //设置文件保存信息

                //设置文件保存路径

                string temPath = "diract" + @"\" + "" + FileName + "" + @"\" + DateTime.Now.Year + @"\" + DateTime.Now.ToString("yyyy-MM-dd") + @"\";

                string pathHead = ConfigurationManager.AppSettings["doc_path"];

                if (string.IsNullOrEmpty(pathHead))

                {

                    pathHead = @"D:\Uploads\MIS\";

                }

                string path = pathHead + temPath;

                if (!Directory.Exists(path))

                {

                    Directory.CreateDirectory(path);

                }

                ///'可根据扩展名字的不同保存到不同的文件夹

                ///注意:可能要修改你的文件夹的匿名写入权限。

                fileName = DateTime.Now.Ticks.ToString() + fileName;

                postedFile.SaveAs(path + fileName);

                imgPathPart = temPath + fileName;

            }

            else

            {

                imgPathPart = null;

            }

           

        }

        catch (System.Exception Ex)

        {

        }

        return imgPathPart;

    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: