<!DOCTYPE html> <html> <head> <title>HTML5上传图片预览</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script src="/js/jquery.js"></script> </head> <body> <h3>请选择图片文件:JPG/GIF</h3> <form name="form0" id="form0" runat="server" enctype="multipart/form-data" > <input type="file" name="file0" id="file0" multiple="multiple" /><br><img src="" id="img0" > <asp:Button ID="Button1" runat="server" Text="保存" onclick="Button1_Click" /> <script> $("#file0").change(function(){ var objUrl = getObjectURL(this.files[0]) ; console.log("objUrl = "+objUrl) ; if (objUrl) { $("#img0").attr("src", objUrl) ; } }) ; //建立一個可存取到該file的url function getObjectURL(file) { var url = null ; if (window.createObjectURL!=undefined) { // basic url = window.createObjectURL(file) ; } else if (window.URL!=undefined) { // mozilla(firefox) url = window.URL.createObjectURL(file) ; } else if (window.webkitURL!=undefined) { // webkit or chrome url = window.webkitURL.createObjectURL(file) ; } return url ; } </script> </form> </body> </html>
后台:
using System.IO; using System.Drawing; public partial class demo : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } //保存图片 protected void Button1_Click(object sender, EventArgs e) { HttpPostedFile imgfile = Request.Files["file0"]; imgfile.SaveAs(Server.MapPath("~/abc.jpg")); } }
如图:
说明:表单中enctype="multipart/form-data"的意思,是设置表单的MIME编码。默认情况,这个编码格式是application/x-www-form-urlencoded,不能用于文件上传;只有使用了
multipart/form-data,才能完整的传递文件数据。