我試圖讓客戶端上傳文件到我的服務器在ASP.NET C#網站。我創建了一個簡單的腳本來向我介紹上傳文件和創建腳本的細節,其中所有代碼(HTML和C#代碼)都位於同一個文件中。上傳文件腳本不會加載,因爲它找不到函數bt1Clicked()
我的問題:功能uploadFile()
從不輸出/返回任何字符串結果時,它應該返回一個字符串描述如果上傳成功或失敗的原因。
我在做什麼錯?
PS:我已經更新我用下面的代碼的web.config:
<appSettings>
<add key="folderPath" value="uploadedFiles"></add>
</appSettings>
PPS:這有什麼錯讓所有在同一.aspx文件我的C#代碼& HTML?將它們分離出來會更好嗎?
我的簡單代碼:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="test.aspx.cs" Inherits="WebApplication1.test" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/C#">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
protected global::System.Web.UI.HtmlControls.HtmlInputFile fileUpload;
protected global::System.Web.UI.WebControls.Label lblMessage;
protected global::System.Web.UI.WebControls.Button btnSave;
protected global::System.Web.UI.HtmlControls.HtmlGenericControl test;
protected void bt1Clicked(Object sender, EventArgs e)
{
if (fileUpload.PostedFile != null)
{
string strFilename, strMessage;
strFilename = fileUpload.PostedFile.FileName.ToString();
strMessage = uploadFile(strFilename, ConfigurationManager.AppSettings["folderPath"]);
output.InnerHtml = strMessage;
}
}
public string uploadFile(string fileName, string folderName)
{
if (fileName == "")
{
return "Invalid filename supplied";
}
if (fileUpload.PostedFile.ContentLength == 0)
{
return "Invalid file content";
}
fileName = System.IO.Path.GetFileName(fileName);
if (folderName == "")
{
return "Path not found";
}
try
{
if (fileUpload.PostedFile.ContentLength <= 2048000)
{
fileUpload.PostedFile.SaveAs(Server.MapPath(folderName) + "\\" + fileName);
return "File uploaded successfully";
}
else
{
return "Unable to upload,file exceeds maximum limit";
}
}
catch (UnauthorizedAccessException ex)
{
return ex.Message + "Permission to upload file denied";
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="fileUpload" type="file" Runat="server" NAME="fileUpload"/>
<asp:button id="btnSave" runat="server" Text="Upload File" OnClick="bt1Clicked"></asp:button>
<p id="output" runat="server">Result should be displayed here after clicking</p>
</div>
</form>
</body>
</html>