利用input file 上传文件调用ajax保存到服务器(含后台代码)
html页(以上传图片为例):<input id="file" type="file" accept="image/png,image/gif" name="file" />
上传按钮事件:
var formData = new FormData();
formData.append('file', $('#file')[0].files[0]);
$.ajax({
url: "Handler1.ashx",
type: 'POST',
cache: false,
data: formData,
//timeout: 180000,
processData: false,
contentType: false,
dataType: "json",
success: function (result) {
//成功!
},
error: function (err) {
//失败!
}
});
一般处理程序Handler1.ashx后台代码:
public void ProcessRequest(HttpContext context)
{
System.Web.HttpRequest request = context.Request;
string path = System.Configuration.ConfigurationManager.AppSettings["TempPath"].ToString();//文件保存的路径
HttpPostedFile PtFile = context.Request.Files["file"];
string filename = DateTime.Now.ToString("yyyyMMddHHmmss") + PtFile.FileName ;
PtFile.SaveAs(path + filename);
context.Response.Write("");
}
accept表示可以选择的文件类型,多个类型用英文逗号分开,常用的类型如下:
*.3gpp audio/3gpp, video/3gpp
*.ac3 audio/ac3
*.asf allpication/vnd.ms-asf
*.au audio/basic
*.css text/css
*.csv text/csv
*.doc application/msword
*.dot application/msword
*.dtd application/xml-dtd
*.dwg image/vnd.dwg
*.dxf image/vnd.dxf
*.gif image/gif
*.htm text/html
*.html text/html
*.jp2 image/jp2
*.jpe image/jpeg
*.jpeg image/jpeg
*.jpg image/jpeg
*.js text/javascript, application/javascript
*.json application/json
*.mp2 audio/mpeg, video/mpeg
*.mp3 audio/mpeg
*.mp4 audio/mp4, video/mp4
*.mpeg video/mpeg
*.mpg video/mpeg
*.mpp application/vnd.ms-project
*.ogg application/ogg, audio/ogg
*.pdf application/pdf
*.png image/png
*.pot application/vnd.ms-powerpoint
*.pps application/vnd.ms-powerpoint
*.ppt application/vnd.ms-powerpoint
*.rtf application/rtf, text/rtf
*.svf image/vnd.svf
*.tif image/tiff
*.tiff image/tiff
*.txt text/plain
*.wdb application/vnd.ms-works
*.wps application/vnd.ms-works
*.xhtml application/xhtml+xml
*.xlc application/vnd.ms-excel
*.xlm application/vnd.ms-excel
*.xls application/vnd.ms-excel
*.xlt application/vnd.ms-excel
*.xlw application/vnd.ms-excel
*.xml text/xml, application/xml
*.zip aplication/zip
*.xlsx application/vnd.openxmlformats-officedocument.spreadsheetml.sheet