我正在尝试使用AJAX上传文件问题是我是.net中的新手而且不知道我是否做得对,所以我感谢任何帮助或建议。
这是我的HTML代码:
<asp:FileUpload ID="FileUpload1" onChange="Show()" runat="server" />
用户选择文件时应调用我的方法
这是我在MSDN中找到的脚本:
<script type="text/javascript">
function Show() {
var file = document.getElementById("FileUpload1");
alert("test")
$.ajax({
type: "POST",
url: "SendSms.aspx/StaticUpdate",
data: '{name:"test" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert("test1");
}
});
}
function OnSuccess(response) {
alert("test2");
}
</script>
这是我的ASP方法:
[System.Web.Services.WebMethod]
public static void StaticUpdate()
{
SendSms upload = new SendSms();
upload.Upload();
}
public void Upload()
{
string FileName = System.DateTime.Now.ToString("ddmmyyhhmmsss") + FileUpload1.FileName;
if (IsPostBack)
{
Boolean fileOK = false;
String path = Server.MapPath("~/Upload/");
if (FileUpload1.HasFile)
{
String fileExtension =
System.IO.Path.GetExtension(FileName).ToLower();
String[] allowedExtensions = { ".txt" };
for (int i = 0; i < allowedExtensions.Length; i++)
{
if (fileExtension == allowedExtensions[i])
{
fileOK = true;
}
}
}
if (fileOK)
{
try
{
FileUpload1.PostedFile.SaveAs(path
+ FileName);
System.IO.StreamReader myFile =
new System.IO.StreamReader("C:\\inetpub\\wwwroot\\Viber_Bulk_UI\\Upload\\" + FileName + "");
TextBox2.Text = myFile.ReadToEnd();
myFile.Close();
string Path = "C:\\inetpub\\wwwroot\\Viber_Bulk_UI\\Upload\\" + FileName + "";
System.IO.File.Delete(Path);
}
catch (Exception ex)
{
Label1.Text = "File could not be uploaded.";
}
}
else
{
Label1.Text = "Cannot accept files of this type.";
}
}
}
我得到的错误是:
NullReferenceException未被用户代码处理。 对象引用未设置为对象的实例。
提前致谢
答案 0 :(得分:0)
string filename = System.IO.Path.GetFileName(FileUpload1.FileName);
string ext = System.IO.Path.GetExtension(FileUpload1.FileName);
if (fileExtension == ".txt"){
using (System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath(("C:\\inetpub\\wwwroot\\Viber_Bulk_UI\\Upload\\" + FileName), System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.Read, 8, System.IO.FileOptions.None))
{
byte[] data = System.Text.Encoding.ASCII.GetBytes(FileName);
fs.Write(data, 0, data.Length);
fs.Flush();
fs.Close();
}
}