1、调出客户端选择文件:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="HB.aspx.cs" Inherits="QrPaySystem.PageHB.HB" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form2" runat="server">
<div>
<br />
<br />
<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
<br />
<%--为按钮添加onclick响应逻辑--%>
<input type="button" name="button" value="点我就像点击“浏览”按钮一样" onclick="javascript: Upload_openBrowse();" />
<br />
<br />
<br />
<img src="../tools/HB_pic/adding_hb.png" alt="添加您的红包码" width="329" height="495" onclick="javascript:Upload_openBrowse();" />
<br />
<br />
<asp:Button ID="UploadButton" runat="server" OnClick="UploadButton_Click" Text="上传文件" />
<br />
<br />
<asp:Label ID="UploadStatusLabel" runat="server">文件路径:</asp:Label>
<br />
<br />
</div>
</form>
</body>
<script type="text/javascript">
// 打开上传文件浏览
function Upload_openBrowse()
{
var ie = navigator.appName == "Microsoft Internet Explorer" ? true : false;
if (ie)
{
document.getElementById("FileUpload1").click(); // 通过document元素点击FileUpload控件
//document.getElementById("filename").value = document.getElementById("FileUpload1").value;
}
else
{
var a = document.createEvent("MouseEvents");//FF的处理
a.initEvent("click", true, true);
document.getElementById("FileUpload1").dispatchEvent(a);
}
}
</script>
</html>
2、上传文件至服务器
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplicationTest
{
public partial class Upload : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
/// <summary>
/// 上传选择的文件至服务器
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void UploadButton_Click(object sender, EventArgs e)
{
// 设置文件保存目录
string appPath = Request.PhysicalApplicationPath + @"Uploads\";
if (!System.IO.Directory.Exists(appPath)) System.IO.Directory.CreateDirectory(appPath);
if (FileUpload1.HasFile)
{
String fileName = FileUpload1.FileName;
string savePath = appPath + Server.HtmlEncode(FileUpload1.FileName); // 生成保存路径
FileUpload1.SaveAs(savePath); // 保存文件
UploadStatusLabel.Text = "Your file was saved as ->" + savePath;
}
else
{
UploadStatusLabel.Text = "You did not specify a file to upload.";
}
}
}
备注:uploadFile控件隐藏