图片上传到服务器

时间:2020-12-02 12:17:21

图片转byte[]:

            string str = @"D:\1.png";
            //读文件
            FileStream fs = new FileStream(str, FileMode.Open, FileAccess.Read);
            BinaryReader by = new BinaryReader(fs);
            int length = (int)fs.Length;
            //转成byte[]
            byte[] imgbyte = by.ReadBytes(length);


把byte[]保存为图片类型(如果byte[]不正确则可能保存报错)

            //转成IO流
            MemoryStream ms = new MemoryStream(imgbyte);
            ms.Seek(0, SeekOrigin.Begin);
            //通过流生成图片
            Image image1 = Image.FromStream(ms);
            //保存
            image1.Save(@"D:\test.png");


图片上传到服务器(App POST传到后台):

                string fPath = context.Server.MapPath("severphotes");  //服务器路径
                #region 上传头像
                if (!Directory.Exists(fPath))				//判断是否存在文件夹
                {
                    Directory.CreateDirectory(fPath);
                }

                TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);   //时间戳
                string name = Convert.ToInt64(ts.TotalSeconds).ToString() + ".png";     //图片名
                //if (!File.Exists(fPath + name))
                //{
                System.IO.Stream stream = context.Request.InputStream;		//得到传来的流
                byte[] buffer = new byte[stream.Length];
                FileStream fs = null;
                try
                {
                    fs = new FileStream(fPath + "//" + name, FileMode.Create);       //按照路径创建图片文件
                    while ((stream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        fs.Write(buffer, 0, buffer.Length);			//写入数据
                    }
                }
                catch (IOException ioe)
                {
                    context.Response.Write(ioe);
                }
                finally
                {
                    if (fs != null)
                    {
                        fs.Close();
                    }
                    stream.Close();
                }

Form表单提交(input控件添加图片)保存到服务器

1、

            System.Web.HttpFileCollection files = context.Request.Files;   //获取FORM表单提交的文件
            if (files.Count > 0)
            {
                System.Web.HttpPostedFile postedfile = files[0];
                Stream str = postedfile.InputStream;
                StreamReader streamReader = new StreamReader(str);
                byte[] bytes = new byte[1024];
                //地址名字
                TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                string name = Convert.ToInt64(ts.TotalSeconds).ToString() + ".png";
                string fPath = "";
                string url = ""; 
                string tag = "";
                string imgName = "";
                if (files.AllKeys[0] == "icon")
                {
                    fPath = context.Request.MapPath("../../../severphotes");
                    url = ConfigurationManager.AppSettings["website"].ToString() + "severphotes/" + name;
                    tag = "severphotes/" + name;
                    imgName = "SF_ICON";
                }
                #region 保存图片方法
                FileStream fstr = new FileStream(fPath + "//" + name, FileMode.OpenOrCreate, FileAccess.Write);
                int len = 0;
                while ((len = str.Read(bytes, 0, 1024)) > 0)
                {
                    fstr.Write(bytes, 0, len);
                }
                streamReader.Dispose();
                str.Dispose();
                fstr.Flush();
                fstr.Close();
                #endregion
                context.Response.ContentType = "text/html";   //这种方式返回能调用JS
            }

2、自带Save:

System.Web.HttpFileCollection files = context.Request.Files;
            if (files.Count > 0)
            {
                TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                string name = Convert.ToInt64(ts.TotalSeconds).ToString() + ".png";
                string tag = "image/forward/" + name;
                string url = ConfigurationManager.AppSettings["website"].ToString() + tag;
                HttpPostedFile hpFile = files[0];
                hpFile.SaveAs(context.Request.MapPath("../../../image/forward/" + name));
                context.Response.ContentType = "text/html";
                context.Response.Write("<script>parent.setPic('" + url + "','" + tag + "')</script>");       //在iframe中调用主页面的script需要加parent.
            }

HTML部分:

    function setPic(url, tag) {  //给图片赋值路径和tag属性,src是为了显示,tag是在数据库保存的相对路径
        $('#forwardImg').attr("src", url);
        $('#forwardImg').attr("tag", tag);
    }

    function upload() { //图片上传后提交form
        $('#form').submit();
    }

    function uploadImg() {  //控件模拟点击,也可以$("#img").click();
        document.getElementById('img').click();
    }

 <form target="filetarget" enctype="multipart/form-data" method="post" id="form" action="../dzxswebservice/ForwardService.ashx?action=updateImage">
     <div style="text-align:left;margin-top:40px;">
         <a onclick="uploadImg()">
             <i class="icon-shangchuan  iconfont"></i>
                 <input type="file" onchange="upload()" name="img1" id="img" style="display:none"/>上传图片
           </a>
     </div>
     <iframe name="filetarget" id="filetarget" style="display: none"></iframe>
  </form>
样式什么的可以不看,主要的是form、input、iframe、a标签

这里需要给form添加 enctype="multipart/form-data" 否则无法上传

这里第一次点击触发的是uploadImg方法,input就会显示选择文件,确认选择后则自动触发onchange事件提交。在后台可以限制文件大小。