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的控件不可以被赋值!(安全问题!)