HttpContext.Current.Server.MapPath
<asp:FileUpload ID="FileUpload1" runat="server" /> <asp:Button ID="btnUpload" runat="server" OnClick="btnUpload_Click" Text="上传" /> <asp:Label ID="resultlbl" runat="server"></asp:Label> <body> <div style="position:static;"> <div class="style1"> 演示文件上传控件 </div> <div class="style1"> <asp:FileUpload ID="File1" runat="server"/> <asp:Button ID="UploadBtn" runat="server" onclick="Button1_Click" Text="上传" /> </div> </div> <asp:Label ID="Label1" runat="server" Width="437px" Height="61px"></asp:Label> </body>
protected void btnUpload_Click(object sender, EventArgs e) { Boolean fileOk = false; string path = Server.MapPath("~/upload/"); //判断是否已经选取文件 if (FileUpload1.HasFile) { //取得文件的扩展名,并转换成小写 string fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower(); //限定只能上传jpg和gif图片 string[] allowExtension = { ".jpg", ".gif", ".txt", ".xls" }; //对上传的文件的类型进行一个个匹对 for (int i = 0; i < allowExtension.Length; i++) { if (fileExtension == allowExtension[i]) { fileOk = true; break; } } // if (fileOk) { resultlbl.Text = "要上传的文件类型不对!"; } //对上传文件的大小进行检测,限定文件最大不超过1M if (FileUpload1.PostedFile.ContentLength > 1024000) { fileOk = false; } //最后的结果 if (fileOk) { try { FileUpload1.PostedFile.SaveAs(path + FileUpload1.FileName); resultlbl.Text = "上传成功"; } catch { resultlbl.Text = "上传失败"; } } else { resultlbl.Text = "文件类型或者文件大小超出1M或者文件类型不对"; } } } protected void Button1_Click(object sender, EventArgs e) { string FileName = File1.PostedFile.FileName; string file_str = "文件名称:" + FileName + "<br>"; file_str = "文件类型:" + File1.PostedFile.ContentType + "<br>"; file_str = "文件长度:" + File1.PostedFile.ContentLength.ToString() + "KB<br>";
//上传文件到服务器 string upload_file = HttpContext.Current.Server.MapPath("~/789/123") + FileName;//取出服务器虚拟路径,文件存储在服务器上传的路径 File1.PostedFile.SaveAs(upload_file);//开始上传文件
Label1.Text = file_str + "<a href='" + upload_file + "' target='_blank' >" + FileName + "</a>" + "上传文件成功";//获取的名字带链接
Label1.Text = file_str + "<a href='#'>"+FileName+"</a>" + "上传文件成功";//获取的名字带链接 } } }