在服务器端onClick事件中使用asp.net fileupload字符串。在asp.net后面的代码中访问输入控件的类型文件
ASP.Net文件上传控制
<asp:FileUpload ID="btnFileUpload" runat="server" Width="0px" onchange="this.form.lblUploadStatus.value=GetFileName(this.value);"/>
<asp:TextBox ID="txtUploadStatus" runat="server" Width="680px"></asp:TextBox>
的Javascript
<script type="text/javascript">
function GetFileName(val) {
var i = val.lastIndexOf("\\");
$get('<%= txtUploadStatus.ClientID %>').value = val;
return true;
}
</script>
.NET
using (SqlConnection dbConnection = new SqlConnection(CKS_app_settings.sql_conn_string_db))
{
try
{
dbConnection.Open();
SqlCommand command = new SqlCommand(sSQL, dbConnection);
//command.Transaction = tn;
command.CommandText = sSQL;
command.CommandType = CommandType.StoredProcedure;
command.CommandTimeout = 1024;
// Split entire file path to grab filename
string[] split = txtUploadStatus.Text.Split(new char[] { '\\' });
string fileName = split[06];
command.Parameters.AddWithValue("@p_filename", fileName);
command.Parameters.AddWithValue("@p_url", txtUrl.Text);
command.Parameters.AddWithValue("@p_Title", txtImgTitle.Text);
command.Parameters.AddWithValue("@p_alt_text", txtAlt.Text);
int rowsAffected = command.ExecuteNonQuery();
}
catch (SqlException ex)
{
// throw ex;
//If it failed for whatever reason, rollback the //transaction
//tn.Rollback();
//No need to throw because we are at a top level call and //nothing is handling exceptions
result = ex.InnerException.Message;
}
}
也许有一个更好的解决方案,但最终对我有用,因为我想插入数据到数据库中,并使用system.io在单击事件中将新文件写入路径。
我尝试这样做,我收到了一条“未将对象引用设置到对象的实例。 “例外。是否有一个对象需要先构造? – 2012-01-04 15:12:45
@nickgowdy,让我猜 - 你的FileUpload控件嵌套在UpdatePanel中吗? – Shai 2012-01-04 17:32:02
我的FileUpload不是嵌套在更新面板之间,而是在该页面上使用一个。如果有帮助,我已经更新了原始文章以显示整个页面标记。 – 2012-01-05 08:41:19