高分求教,请问ASP.NET如何通过表单上传图片文件。
因为我的网站都是用AJAX来做的,全部都是静态页面,所以FileUpload等服务器控件用不了,只能采用表单上传的方式来上传图片文件。但是我对表单上传的原理过程不是很了解。
求详细的客户端代码和后台处理代码,谢谢!!!

解决方案 »

  1.   

    带有图片预览功能的上传表单,完整的HTML代码如下所示
    <html>       
    <head>       
    <meta http-equiv="Content-Type" content="text/html; charset=gb2312">       
    <title>带有图片预览功能的上传表单it.com.cn</title>       
    <script>       
    function viewmypic(mypic,imgfile) {        
    if (imgfile.value){        
    mypic.src=imgfile.value;        
    mypic.style.display="";        
    mypic.border=1;        
    }        
    }        
    </script>       
    </head>       
    <body>       
    <center>       
    <form >       
    <input name="imgfile" type="file" id="imgfile" size="40" onchange="viewmypic(showimg,this.form.imgfile);" />       
    <br />       
    </form>       
    <img name="showimg" id="showimg" src="" style="display:none;" alt="预览图片" />       
    <br />       
    </div>       
    <div style="display:none">       
    </div>       
    </center>       
    </body>       
    </html> 文章来源:http://www.knowsky.com/347503.html
      

  2.   

    http://hi.baidu.com/loveyoursmile/blog/item/f7940b24ff8fe037c8955930.html
      

  3.   


    <html> <body> <center> 
       <form name="mainForm" enctype="multipart/form-data" action="process.asp" method=post>     <input type=file name=mefile><br>    <input type=submit name=ok value="OK">    </form> 
    </center> 
    </body> 
    </html> 这里面唯一要注意的是enctype="multipart/form-data"这个属性,这个属性表明我们的表单是多类型数据格式,而不是byte格式的
      

  4.   

    要做成刷新的,好像只能用框架来做了!昨天在网上淘到一个无刷新ajax大文件批量上传控件,经研究发现和FCKEDITOR原理差不多,也是框架形式!不过性能特别好!楼主可以到网上搜一下!他把js,和页面代码全封装成一个DLL文件,拿来简单配置一下就可以用了!(上周我到书店查过了!所以ajax书上用的无刷新上传控件都是用框架形式来做的,不过有的你能看的出来有的你看不出来罢了比如我们常用的文本编辑器如fckeditor,freetextbox都是如此)另外还有一种办法就是用flash来实现,不过在不同的浏览器下不是太好外理兼容性!
      

  5.   

    AJAX和静态没有什么关系啊?反正你接受提交的一定是动态页面,通过Page.PostedFile能够读取页面提交上来的文件,即使是非runat="server"的input。
      

  6.   

    用 客户端的上传控件, 加上 runat=server.(不要忘记了) submit 提交之后,在 后台,获取 ,后台代码:
        HttpFileCollection files = HttpContext.Current.Request.Files;    for (int iFile = 0; iFile < files.Count; iFile++)
        {           
         HttpPostedFile postedFile = files[iFile];     string fileName,newfilename, fileExtension,filepath,savefilepath;
         fileName = System.IO.Path.GetFileName(postedFile.FileName);
         if (fileName != "")
         {
          fileExtension = System.IO.Path.GetExtension(fileName); 
          newfilename=System.DateTime.Now.ToString("yyyyMMddhhmmssffff")+fileExtension;
          filepath=System.Web.HttpContext.Current.Request.MapPath("files/") + newfilename;
          savefilepath="files/"+newfilename;
          postedFile.SaveAs(filepath);
          insert(fileName,savefilepath,fileExtension);
         }
      

  7.   

    全是html的,那ajax怎么用的.
    如果你要全是html的话,那就直接全用javascript写
      

  8.   


    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="FileUp.aspx.cs" Inherits="FileUp" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>无标题页</title>
        <link href="css/css.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <br />
            <br />
            <asp:Panel ID="Panel1" runat="server" Height="366px" Width="631px">
                <div style="text-align: center">
                    <br />
                    <table border="0" style="width: 462px">
                        <caption>
                        </caption>
                        <tr>
                            <td style="width: 182px; height: 40px" align="right" >
                                请填写文件名称:</td>
                            <td style="height: 40px" align="left" >
                                <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
                                <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtName"
                                    ErrorMessage="请填写文件名称">*</asp:RequiredFieldValidator></td>
                        </tr>
                        <tr>
                            <td style="width: 182px; height: 40px" align="right" >
                                请填写文件描述:</td>
                            <td style="height: 40px" align="left" >
                                <asp:TextBox ID="txtDescript" runat="server"></asp:TextBox>
                                <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtDescript"
                                    ErrorMessage="请填写文件名称">*</asp:RequiredFieldValidator></td>
                        </tr>
                        <tr>
                            <td style="width: 182px; height: 40px" align="right" >
                                请选择文件路径:</td>
                            <td style="height: 40px" align="left" >
                                <input id="File1" runat="server" type="file" /></td>
                        </tr>
                        <tr>
                            <td colspan="2" align="center" style="height: 53px">
                                <asp:ImageButton ID="btnSubmit" runat="server" ImageUrl="~/Images/提交.gif" OnClick="btnSubmit_Click" />
                                <asp:ImageButton ID="btnReset" runat="server" ImageUrl="~/Images/重设.gif" CausesValidation="False" OnClick="btnReset_Click" /></td>
                        </tr>
                    </table>
                </div>
                <asp:ValidationSummary ID="ValidationSummary1" runat="server" ShowMessageBox="True"
                    ShowSummary="False" />
            </asp:Panel>
            &nbsp;</div>
        </form>
    </body>
    </html>
      

  9.   


    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;public partial class FileUp : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["Name"] == null)
            {
                JS.Alert("您还未登陆或登陆超时!");
                Response.Redirect("Default.aspx");
            }
        }
        protected void btnReset_Click(object sender, ImageClickEventArgs e)
        {
            txtName.Text = "";
            txtDescript.Text = "";
        }
        /// <summary>
        /// 执行上传文件的判断
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSubmit_Click(object sender, ImageClickEventArgs e)
        {
            
            if ("" != File1.PostedFile.FileName)
            {
                string publisher = Session["Name"].ToString();
                DateTime time = DateTime.Now;
                string name = txtName.Text;
                string descript = txtDescript.Text;
                string path = File1.PostedFile.FileName;
                string filetype = path.Substring(path.LastIndexOf(".") + 1);
                string filename = name+DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + "." + filetype;
                if ((filetype == "rar")||(filetype == "exe")||(filetype == "doc")||(filetype == "xls")||(filetype == "ppt"))
                {
                    try
                    {
                        string size = (File1.PostedFile.ContentLength/1024).ToString()+"KB";
                        File1.PostedFile.SaveAs(Server.MapPath("~/upFiles") + "\\" + filename);
                        
                        if (Resource.InsertResourceInfo(filename, descript, publisher, time,size, filetype))
                        {
                            JS.Alert("文件上传成功!");
                        }
                    }
                    catch (Exception e3)
                    {
                        Response.Write(e3);
                        JS.Alert("对不起,您上传的文件过大!");
                    }
                }
                else
                {
                    JS.Alert("请上传格式为rar,exe,doc,xls,ppt的附件!");
                    return;
                }
            }
            else
            {
                JS.Alert("请选择文件路径!");
            }
        }
    }
      

  10.   


    <%@ language="javascript" %><html>
    <head>
        <title>上传图片文件</title>
        <meta http-equiv="Content-Type" content="text/html; charset=GB2312">
    </head>
    <body>
    <%//保存路径
    var spath = "images/";var self = Request.ServerVariables("SCRIPT_NAME");
    if ((Request.ServerVariables("REQUEST_METHOD") + "").toLowerCase()=="post")
    {
     var fmLen = Request.TotalBytes;
     var fmCont = Request.BinaryRead(fmLen);
     var ext = getExt(fmCont);
        var msg = "Not Allow Extension Of " + ext + " , Upload Fail !";    if (/\.(rar|bmp|jpg|gif)/i.test(ext))
        {
      var stm = Server.CreateObject("ADODB.Stream");
      stm.Type = 1;
      stm.Mode = 3;
      stm.Open;
      stm.Write(fmCont);
      var s = stm.Position = getStart(fmCont);
      var bstr = stm.Read(fmLen - s - 47);
      var fileName = new Date().valueOf() + ext;
      stm.Close();
      stm.Open();
      stm.Write(bstr);
      stm.SaveToFile(Server.MapPath(spath + fileName));
      stm.Close();
      stm = null;
      msg = "Upload File Succeed !";
     } Response.Write("\
     <script type=\"text/javascript\">\
      window.alert(\""+msg+"\");\
      window.opener.sform.content.value += \"\\r\\n<img src=\\\"/Myart/images/" + fileName + "\\\">\";\
      window.close();\
      location.replace(\"" + self + "\");\
     </script>");
    }
    function getExt(bstr)
    {
     var stm = Server.CreateObject("ADODB.Stream");
     stm.Type = 2;
     stm.Mode = 3;
     stm.Open();
     stm.WriteText(bstr);
     stm.Position = 0;
     stm.CharSet = "GB2312";
     var fmText = stm.ReadText();
     stm.Close();
     stm = null;
     return /filename=\".+(\..+)\"/.exec(fmText)[1];
    }
    %>
    <script language="vbscript" runAt="server">
    function getStart(bstr) : getStart = InStrB(1, bstr, ChrB(13) & ChrB(10) & ChrB(13) & ChrB(10)) + 3 : end function
    </script><form action="<%= self %>" method="post" enctype="multipart/form-data" onsubmit="return (this.upFile.value!='');"> 
        <input type="file" name="upFile" />
        <input type="submit" value="上传文件" />
    </form></body>
    </html>