html中使用表单和input file上传图片

本文转载自:http://hi.baidu.com/love_1210/item/120e452b42b2a854c38d59eb

 

客户端代码:

 <form name="form1" method="post" enctype="multipart/form- data" action="requestfile/asprece.aspx">//如果file框没有加runat="server",则 form里一定要加上 enctype="multipart/form-data"这样才可以实现上传文件到服务器;使用了server和没有使用 

runat="server"是有区别的.使用了runat="server"的form编译后,action必定是指向本身的网页。而没

有加runat="server"的form可以指向一个网页。

 


        <input type="file" name="file1" style="width:160px;" />
        <input type="submit" name="Submit" value="添加" />
    </form>

服务器端代码:

  private string retvalue = "ok";
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                HttpPostedFile req = Request.Files["file1"];
                if (req == null || req.ContentLength < 0)
                {

                    Response.Write("没有文件");
                    Response.End();
                }
                else
                {
                    try
                    {

                       string extion = System.IO.Path.GetExtension(req.FileName.ToString());
                        string date = DateTime.Now.ToString("yyyyMMddhhmmss").ToString();
                        string src = date + extion;
                        string pathnew = Server.MapPath("~/testfile/");
                        req.SaveAs(pathnew+src);        //自带的方式保存文件

                        /*读取文件流保存

                         Stream stream = req.InputStream;
                        //string src = "test.xls";
                        string fullpathnew = pathnew + src;

                        if (!Directory.Exists(pathnew))
                        {
                            Directory.CreateDirectory(pathnew);
                        }

                        BinaryReader br = new BinaryReader(stream);
                        byte[] fileByte = br.ReadBytes((int)stream.Length);
                        // string content = fileByte.ToString();
                        using (FileStream fileStream = new FileStream(fullpathnew, FileMode.Create))
                        {
                            fileStream.Write(fileByte, 0, fileByte.Length);
                        }*/

                    }
                    catch (Exception es)
                    {
                        retvalue = es.Message.ToString();

                    }
                    finally 
                    {
                        Response.Write(retvalue);
                    }
                }
            }

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。