打赏

html5 file 上传图片

 

说明:开发环境 vs2012 mvc4项目,后台语言csharp

1、前端代码

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>图片上传测试</title>
</head>
<body>
<form action="/Home/MultiSavePage" enctype="multipart/form-data" method="post"> 
<input type="file" name="files" id="file1" onchange="checkPic(this)" /><br/> 
<input type="file" name="files" id="file2" onchange="checkPic(this)"/><br/> 
<input type="file" name="files" id="file3" onchange="checkPic(this)"/><br/> 

<input type="submit" value="同时上传多个文件" /> 
</form> 
<script type="text/javascript">
function checkPic(e) { 
if (!e || !e.value) return;
var patn = /\.jpg$|\.jpeg$|\.png$|\.gif$/i;
if (!patn.test(e.value)) {
alert("您选择的似乎不是图像文件。");
e.value = "";
return;
}
else {
//以下的代码可以 把选中的图片 放到img中显示
var $file = $(e);
var fileObj = $file[0];
var windowURL = window.URL || window.webkitURL;
var dataURL; 
//var $img = $("#"+id+"");
if (fileObj && fileObj.files && fileObj.files[0]) {
dataURL = windowURL.createObjectURL(fileObj.files[0]);
console.log(dataURL);
//$img.attr('src', dataURL);
}
}
}
</script>
</body>
</html>

2、控制器代码

action="/Home/MultiSavePage" 对应的后台代码 

(1)、正常保存图片,不对图片压缩处理

        public void MultiSavePage(IEnumerable<HttpPostedFileBase> files)
        {
            Int32 count = files.Count();
            Int32 pid = 56;
            Int32 offid = 100;
            string str = "GX";     
            string pathForSaving = Server.MapPath("~/img");
            string pagePath = pathForSaving + "/" + offid + "/" + str + "/" + pid;
            if (this.CreateFolderIfNeeded(pagePath))
            {
                foreach (var file in files)
                {
                    if (file != null && file.ContentLength > 0)
                    {          
                        string[] picName = file.FileName.Split('.');
                        //判断文件的类型
                        if (picName[1] == "jpg" || picName[1] == "gif" || picName[1] == "png" || picName[1] == "bmg" || picName[1] == "jpeg")
                        {                       
                            //给上传文件重命名
                            string filename = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Guid.NewGuid().ToString();
                           //文件保存的路径
                            string filesavepath =  filename + "." + picName[1];
                            //保存图片
                            //var path = Path.Combine(pathForSaving, file.FileName);
                            var path = Path.Combine(pagePath, filename + "." + picName[1]);
                            file.SaveAs(path);
                        }                   
                    }
                }
            }           
        }

注释:

string pathForSaving = Server.MapPath("~/img"); img是项目文件夹,上传的图片都保存到img文件夹下

 

(2)、对上传的图片压缩处理,并且把图片保存为png格式

   public void MultiSavePage(IEnumerable<HttpPostedFileBase> files)
        {
            Int32 count = files.Count();
            Int32 pid = 56;
            Int32 offid = 100;
            string str = "GX";     
            string pathForSaving = Server.MapPath("~/img");
            string pagePath = pathForSaving + "/" + offid + "/" + str + "/" + pid;
            if (this.CreateFolderIfNeeded(pagePath))
            {
                foreach (var file in files)
                {
                    if (file != null && file.ContentLength > 0)
                    {          
                        string[] picName = file.FileName.Split('.');
                        //判断文件的类型
                        if (picName[1] == "jpg" || picName[1] == "gif" || picName[1] == "png" || picName[1] == "bmg" || picName[1] == "jpeg")
                        {                       
                            //给上传文件重命名
                            string filename = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Guid.NewGuid().ToString();
                           //文件保存的路径
                            string filesavepath =  filename + "." + picName[1];
                            //保存图片
                            //var path = Path.Combine(pathForSaving, file.FileName);
                            var path = Path.Combine(pagePath, filename + "." + picName[1]);
                            //file.SaveAs(path);
                            Bitmap bitmapTem = (Bitmap)Image.FromStream(file.InputStream);//file图片文件转换为bitmap
                         
                          
                            //压缩图片

                            Bitmap bitmapLast = ZoomImage(bitmapTem, 331, 600);
                            bitmapLast.Save(path, System.Drawing.Imaging.ImageFormat.Png);
                        }                   
                    }
                }
            }           
        }

 


3、用到的其他方法
      // 检查是否要创建上传文件夹 
        private bool CreateFolderIfNeeded(string path)
        {
            bool result = true;
            if (!Directory.Exists(path))
            {
                try
                {
                    Directory.CreateDirectory(path);
                }
                catch (Exception)
                {
                    //TODO:处理异常 
                    result = false;
                }
            }
            return result;
        } 

4、压缩图片的方法

using System.Drawing;

    //等比例缩放图片
        //destHeight 331 destWidth 600
        private Bitmap ZoomImage(Bitmap bitmap, int destHeight, int destWidth)
        {
            try
            {
                System.Drawing.Image sourImage = bitmap;
                int width = 0, height = 0;
                //按比例缩放           
                int sourWidth = sourImage.Width;
                int sourHeight = sourImage.Height;
                if (sourHeight > destHeight || sourWidth > destWidth)
                {
                    if ((sourWidth * destHeight) > (sourHeight * destWidth))
                    {
                        width = destWidth;
                        height = (destWidth * sourHeight) / sourWidth;
                    }
                    else
                    {
                        height = destHeight;
                        width = (sourWidth * destHeight) / sourHeight;
                    }
                }
                else
                {
                    width = sourWidth;
                    height = sourHeight;
                }
                Bitmap destBitmap = new Bitmap(destWidth, destHeight);
                Graphics g = Graphics.FromImage(destBitmap);
                g.Clear(Color.Transparent);
                //设置画布的描绘质量         
                g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                g.DrawImage(sourImage, new Rectangle((destWidth - width) / 2, (destHeight - height) / 2, width, height), 0, 0, sourImage.Width, sourImage.Height, GraphicsUnit.Pixel);
                g.Dispose();
                //设置压缩质量     
                System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters();
                long[] quality = new long[1];
                quality[0] = 100;
                System.Drawing.Imaging.EncoderParameter encoderParam = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
                encoderParams.Param[0] = encoderParam;
                sourImage.Dispose();
                return destBitmap;
            }
            catch
            {
                return bitmap;
            }
        }

 

 

 

posted @ 2019-01-07 17:40  学习靠自己  阅读(1677)  评论(0编辑  收藏  举报