C# 实现图片上传

C# 实现图片上传


C#实现图片上传:
通过页面form表单提交数据到动作方法,动作方法实现保存图片到指定路径,并修改其文件名为时间格式

页面设置

这里使用的模板MVC自带的模板视图

<h2>上传图片信息</h2>
<form action="/updownImg/UpImage" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" name="" value="上传" />
</form>

上传文件表单必须加上 enctype="multipart/form-data"
否则动作方法接受不到数据

动作方法

[HttpPost]
    public  ActionResult UpImage(HttpPostedFileBase file)
    {
        //上传图片格式数组声明
        string[] fileter =new string[] {".jpg",".png",".jpeg" };
        //保存文件路径
        string path = "/upload/image/"+ DateTime.Now.ToString("yyyyMM");
        //相对程序站点路径
        path = Server.MapPath(path);
        //上传文件后缀
        string fileSuffix = file.FileName.Substring(file.FileName.LastIndexOf(".")).ToLower();
        //保存图片名称以时间格式
        string fileName = DateTime.Now.ToString("yyyyMMddhhmmssms") + fileSuffix;
        //判断上传文件是否是jpg格式,文件大小是否为小于2M
        if (fileter.Contains(fileSuffix) && file.ContentLength <= 20480)
        {
            //判断文件目录是否存在,如果不存在则创建目录
            DirectoryInfo directoryInfo=new DirectoryInfo(path) ;
            if (!directoryInfo.Exists)
            {
                directoryInfo.Create();
            };
            //保存图片
            file.SaveAs(path+"/"+fileName);
            //返回提示保存成功!并返回到首页
            return Content("<script>alert('上传成功');window.location.href='/home/index';</script>");
        }
        //如果文件没通过验证则提示用户上传文件格式不正确并返回到上传页
        return Content("<script>alert('上传文件格式不正确!请核对后重新上传!');window.location.href='/UpdownImg/index';</script>");
        
    }

此动作方法必须采用post请求,利用get则找不到
网页出错

总结:
此动作方法仅为一个模板,修改可实现多图上传及其其他文件上传
在项目中灵活运用

猜你喜欢

转载自www.cnblogs.com/IsThis/p/12814473.html