前端图片文件上传到服务器

这篇博客介绍了如何利用FormData实现前端图片上传到服务器,包括JavaScript代码示例和后台处理方式。同时,还提到了将图片转换为byte[]以及通过Form表单提交图片的方法,强调了form标签设置enctype属性的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

以前ajax不能上传图片 现在有了formdata可以直接ajax上传

代码:

    <form action="DinoVoteHelper.ashx?action=upload" enctype="multipart/form-data" method="post" id="form" target="if">
                    <input style="display: none" id="sfzzm" type="file" name="file1" onchange="javascript:showpic(this,'sfzzmImg');" accept="image/*">
</form>
    <iframe id="if" name="if" style="display:none"></iframe>

js:

        //上传数据
        var formData = new FormData($("#form")[0]);
        $.ajax({
            url: 'DinoVoteHelper.ashx?action=upload',
            type: 'POST',
            data: formData,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success: function (returndata) {
                debugger
                alert(returndata);
            },
            error: function (returndata) {
                alert(returndata);
            }
        });  

后台:

 if (context.Request.Files.Count > 0)
                {
                    string filename = context.Request.Files[0].FileName;//获取文件名 
                    string[] temp = filename.Split('.');//获取文件后缀 
                    string path = "photo/DinoVote/" + my_model.id + "_" + DateTime.Now.ToString("MMddHHmmss") +"."+ temp[1];
                    string strPath = Path.Combine(basePath, path);
                    context.Request.Files[0].SaveAs(strPath);

                    hd_articlevote_images img = new hd_articlevote_images()
                    {
                        hd_code = DinoVoteManage.hd_code,
                        images = path,
                        article_code = my_model.id.ToString()
                    };
                    main_db.hd_articlevote_images.Add(img);
                    main_db.SaveChanges();
                }

图片转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事件提交。在后台可以限制文件大小。



 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值