Create your own Ajax image upload (not available on the Internet)

Time:2021-5-7

Today I need a picture upload plug-in, but the Internet does not provide a meet their needs and easy to use. So I wrote one myself.

Method 1, only use jQuery code, no third-party plug-ins. The code is as follows

<p> 
< label > upload picture 
<input type="text" value="" readonly="readonly" /> 
<input type="button" value="Upload" /> 
</p> 
<script type="text/javascript"> 
$(function() { 
$('.inp_fileToUpload').change(function() { 
var formdata = new FormData(); 
var v_this = $(this); 
var fileObj = v_this.get(0).files; 
url = "/upload/upload_json.ashx"; 
//var fileObj=document.getElementById("fileToUpload").files; 
formdata.append("imgFile", fileObj[0]); 
jQuery.ajax({ 
url : url, 
type : 'post', 
data : formdata, 
cache : false, 
contentType : false, 
processData : false, 
dataType : "json", 
success : function(data) { 
if (data.error == 0) { 
v_this.parent().children(".img_upload").attr("src", data.url); 
//$("#img").attr("src",data.url); 
} 
} 
}); 
return false; 
}); 
}); 
</script>

The disadvantage of this method is that IE6 / 8 / 9 does not support formdata, so this method does not support IE9 or below

Method 2: use ajaxfileupload.js plug-in

Note: this method currently supports IE8 / 9, Google, compatibility is better than method 1. Method 2 is recommended

File upload background processing code (ASP. Net version)

<%@ webhandler Language="C#" %> 

using System; 
using System.Collections; 
using System.Web; 
using System.IO; 
using System.Globalization; 
using LitJson; 
public class Upload : IHttpHandler 
{ 
private HttpContext context; 
public void ProcessRequest(HttpContext context) 
{ 
String aspxUrl = context.Request.Path.Substring(0, context.Request.Path.LastIndexOf("/") + 1); 

//File save directory path 
String savePath = "attached/"; 
//File save directory URL 
String saveUrl = aspxUrl + "attached/"; 
//Defines the file extension that allows uploads 
Hashtable extTable = new Hashtable(); 
extTable.Add("image", "gif,jpg,jpeg,png,bmp"); 
extTable.Add("flash", "swf,flv"); 
extTable.Add("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb"); 
extTable.Add("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2"); 
//Maximum file size 
int maxSize = 1000000; 
this.context = context; 
HttpPostedFile imgFile = context.Request.Files["imgFile"]; 
if (imgFile == null) 
{ 
Showerror ("please select file."); 
} 
String dirPath = context.Server.MapPath(savePath); 
if (!Directory.Exists(dirPath)) 
{ 
Showerror ("upload directory does not exist."); 
} 
String dirName = context.Request.QueryString["dir"]; 
if (String.IsNullOrEmpty(dirName)) { 
dirName = "image"; 
} 
if (!extTable.ContainsKey(dirName)) { 
Showerror ("directory name is incorrect."); 
} 
String fileName = imgFile.FileName; 
String fileExt = Path.GetExtension(fileName).ToLower(); 
if (imgFile.InputStream == null || imgFile.InputStream.Length > maxSize) 
{ 
Showerror ("upload file size exceeds limit."); 
} 
if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(((String)extTable[dirName]).Split(','), fileExt.Substring(1).ToLower()) == -1) 
{ 
Showerror ("upload file extension is not allowed\ N only "+ ((string) exttable [dirname]) +" format is allowed. "); 
} 
//Create folder 
dirPath += dirName + "/"; 
saveUrl += dirName + "/"; 
if (!Directory.Exists(dirPath)) { 
Directory.CreateDirectory(dirPath); 
} 
String ymd = DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo); 
dirPath += ymd + "/"; 
saveUrl += ymd + "/"; 
if (!Directory.Exists(dirPath)) { 
Directory.CreateDirectory(dirPath); 
} 
String newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt; 
String filePath = dirPath + newFileName; 
imgFile.SaveAs(filePath); 
String fileUrl = saveUrl + newFileName; 
Hashtable hash = new Hashtable(); 
hash["error"] = 0; 
hash["url"] = fileUrl; 
context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8"); 
context.Response.Write(JsonMapper.ToJson(hash)); 
context.Response.End(); 
} 
private void showError(string message) 
{ 
Hashtable hash = new Hashtable(); 
hash["error"] = 1; 
hash["message"] = message; 
context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8"); 
context.Response.Write(JsonMapper.ToJson(hash)); 
context.Response.End(); 
} 
public bool IsReusable 
{ 
get 
{ 
return true; 
} 
} 
}