在服務器端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