(轉)html中使用表單和input file上傳圖片

本文轉載自:http://hi.baidu.com/love_1210/item/120e452b42b2a854c38d59eb服務器

 

客戶端代碼:post

 <form name="form1" method="post" enctype="multipart/form- data" action="requestfile/asprece.aspx">//若是file框沒有加runat="server",則 form裏必定要加上 enctype="multipart/form-data"這樣才能夠實現上傳文件到服務器;使用了server和沒有使用 orm

runat="server"是有區別的.使用了runat="server"的form編譯後,action一定是指向自己的網頁。而沒server

有加runat="server"的form能夠指向一個網頁。ip

 


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

服務器端代碼:string

  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)
                {it

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

                       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);                    }                }            }

相關文章
相關標籤/搜索