html+AJAX+ashx 上傳圖片總結
阿新 • • 發佈:2019-01-02
HTML頁面部分程式碼
<img alt="老師相片128*128" width="128px" height="128px" src="../img/ImgTeacher.jpg" id="ImgTeacher" /> <br />
<input type="file" id="fulFile" name="fulFile" accept="image/gif,image/jpeg,image/png" class="file" value="上傳圖片" />
一般處理程式的程式碼
public void ProcessRequest(HttpContext context)
{
context.Response .ContentType = "text/plain";
string msg = string.Empty;
string error = string.Empty;
string result = string.Empty;
string filePath = string.Empty;
string fileNewName = string.Empty;
HttpFileCollection files = context.Request.Files ;
// HttpPostedFile files = context.Request.Files["fulFile"];
if (files.Count > 0)
{
//設定檔名
fileNewName = DateTime.Now.ToString("yyyyMMddHHmmssff") + "_" + System.IO.Path.GetFileName(files[0].FileName);
//儲存檔案
files[0 ].SaveAs(context.Server.MapPath("~/UploadFile_TeacherImg/" + fileNewName));
msg = "檔案上傳成功!";
result = "{msg:'" + msg + "',filenewname:'" + fileNewName + "'}";
}
else
{
error = "檔案上傳失敗!";
result = "{ error:'" + error + "'}";
}
context.Response.Write(result);
context.Response.End();
}
總結:
這裡其實是轉載別人的程式碼然後自己拿來用的,直接拿來用,一直出一些bug:
1.ajax進不去一般處理程式——改動了ashx檔案,他有兩個檔案(.ashx.cs || .ashx)必須用記事本單獨開啟.ashx(
<%@ WebHandler Language="C#" CodeBehind="UploadAjaxImg_Teacher.ashx.cs" Class="PianoManagement.BaseDataManagement.UploadAjaxImg_Teacher" %>//第一行的Class要和你現在的一般處理程式的Class相對應!用記事本改掉
2.AJAX成功了,但是一個拿不到File的值,這裡要檢查一下前臺的File空間有沒有加Name的屬性。
3.File的控制元件不可以被賦值!(安全問題!)