jQuery AjaxUpload upload image code

  • 2020-12-10 00:36:38
  • OfStack

The brushless use AJAXUPLOAD as upload client upload plug-ins, the latest version is 3.9, the official address: http: / / valums com/ajax upload /

In the page introducing jquery. min. 1.4.2. js and ajaxupload js


<script src="Scripts/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="Scripts/ajaxupload3.9.js" type="text/javascript"></script>

HTML code:


<style type="text/css">
#txtFileName {
width: 300px;
}
.btnsubmit{border-bottom: #cc4f00 1px solid; border-left: #ff9000 1px solid;border-top: #ff9000 1px solid; border-right: #cc4f00 1px solid;text-align: center; padding: 2px 10px; line-height: 16px; background: #e36b0f; height: 24px; color: #fff; font-size: 12px; cursor: pointer;}
</style>
 Upload picture: <input type="text" id="txtFileName" /><div id="btnUp" style="width:300px;" class=btnsubmit > browse </div>
<div id="imglist"></div>

js code:


<script type="text/javascript">
$(function () {
var button = $('#btnUp'), interval;
new AjaxUpload(button, {
//action: 'upload-test.php', The address at which the file upload server executes 
action: '/handler/AjaxuploadHandler.ashx',
name: 'myfile',
onSubmit: function (file, ext) {
if (!(ext && /^(jpg|jpeg|JPG|JPEG)$/.test(ext))) {
alert(' The picture format is incorrect , Please select a  jpg  Formatted file !', ' The system prompt ');
return false;
}
// change button text, when user selects file
button.text(' On the cross ');
// If you want to allow uploading only 1 file at time,
// you can disable upload button
this.disable();
// Uploding -> Uploading. -> Uploading...
interval = window.setInterval(function () {
var text = button.text();
if (text.length < 10) {
button.text(text + '|');
} else {
button.text(' On the cross ');
}
}, 200);
},
onComplete: function (file, response) {
//file  Local file name, response  Information returned from the server side 
button.text(' To upload pictures ( Upload only allowed JPG Formatted picture , Must not be larger than 150K)');
window.clearInterval(interval);
// enable upload button
this.enable();
var k = response.replace("<PRE>", "").replace("</PRE>", "");
if (k == '-1') {
alert(' The file you uploaded is too big ! Please do not exceed 150K');
}
else {
alert(" String returned from the server: "+k);
alert(" Local file name: "+file);
$("#txtFileName").val(k);
$("<img />").appendTo($('#imglist')).attr("src", k);
}
}
});
});
</script> 

Server-side ajaxuploadhandler.ashx code


public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
HttpPostedFile postedFile = context.Request.Files[0];
string savePath = "/upload/images/";
int filelength = postedFile.ContentLength;
int fileSize = 163600; //150K
string fileName = "-1"; // Returns the file name after the upload 
if (filelength <= fileSize)
{
byte[] buffer = new byte[filelength];
postedFile.InputStream.Read(buffer, 0, filelength);
fileName = UploadImage(buffer, savePath, "jpg");
}
context.Response.Write(fileName);
}
public static string UploadImage(byte[] imgBuffer, string uploadpath, string ext)
{
try
{
System.IO.MemoryStream m = new MemoryStream(imgBuffer);
if (!Directory.Exists(HttpContext.Current.Server.MapPath(uploadpath)))
Directory.CreateDirectory(HttpContext.Current.Server.MapPath(uploadpath));
string imgname = CreateIDCode() + "." + ext;
string _path = HttpContext.Current.Server.MapPath(uploadpath) + imgname;
Image img = Image.FromStream(m);
if (ext == "jpg")
img.Save(_path, System.Drawing.Imaging.ImageFormat.Jpeg);
else
img.Save(_path, System.Drawing.Imaging.ImageFormat.Gif);
m.Close();
return uploadpath + imgname;
}
catch (Exception ex)
{
return ex.Message;
}
}
public static string CreateIDCode()
{
DateTime Time1 = DateTime.Now.ToUniversalTime();
DateTime Time2 = Convert.ToDateTime("1970-01-01");
TimeSpan span = Time1 - Time2; //span It's the difference between the two dates  
string t = span.TotalMilliseconds.ToString("0");
return t;
}

In the development of PHP website, the file upload function is often used, and I have described how to use PHP to achieve the file upload function. With the development of WEB technology, user experience has become the key to measure the success of websites. Today, I would like to share with you an example of how to realize Ajax-style file uploading in PHP using Jquery. Jquery plug-in Ajaxupload can realize single file and multiple file uploading.

AjaxUpload

AjaxUpload, a plug-in for Jquery, can upload files in Ajax style without creating form forms. Of course, form forms can also be created as needed.

The preparatory work

1. Download Jquery development kit and file upload plug-in AjaxUpload.

2. Created ES64en. html, and introduced Jquery development kit and AjaxUpload plug-in


<script src="js/jquery-1.3.js"></script>
<script src="js/ajaxupload.3.5.js"></script> 

3. According to the requirements of Jquery plug-in AjaxUpload, create an DIV that triggers the file upload function of Ajax


<ul> 
<li id="example"> 
<div id="upload_button"> File upload </div>
<p> A list of uploaded files :</p> 
<ol class="files"></ol>
</ul> 

Note: From the following code we can see that the Jquery plug-in AjaxUpload triggers the file upload function according to upload_button.

Foreground JS code

In the code, I set the switch, which can match the type of uploaded file according to the need, and also can set whether Ajax implements single file upload or multiple file uploads.


$(document).ready(function(){
var button = $('#upload_button'), interval;
var fileType = "all",fileNum = "one"; 
new AjaxUpload(button,{
action: 'do/uploadfile.php',
/*data:{
'buttoninfo':button.text()
},*/
name: 'userfile',
onSubmit : function(file, ext){
if(fileType == "pic")
{
if (ext && /^(jpg|png|jpeg|gif)$/.test(ext)){
this.setData({
'info': ' The file type is image '
});
} else {
$('<li></li>').appendTo('#example .files').text(' Non-image type file, please retransmit ');
return false; 
}
}
button.text(' File on file ');
if(fileNum == 'one')
this.disable();
interval = window.setInterval(function(){
var text = button.text();
if (text.length < 14){
button.text(text + '.'); 
} else {
button.text(' File on file '); 
}
}, 200);
},
onComplete: function(file, response){
if(response != "success")
alert(response);
button.text(' File upload ');
window.clearInterval(interval);
this.enable();
if(response == "success");
$('<li></li>').appendTo('#example .files').text(file); 
}
});
}); 

Note:

Line 1: the $(document).ready () function, in Jquery, similar to window.load, uses this function to call the bound function as soon as DOM is loaded and ready to read and manipulate.

Line 3: The fileType and fileNum parameters represent the type and number of uploaded files. The default value is to upload all types of files, and only one file can be uploaded at the same time. If you want to upload picture files or multiple files at the same time, you can change the two variable values to pic and more.

Line 6-8: POST to server data. You can set static values or get dynamic values from Jquery's DOM operation function, such as INPUT in the form form.

Line 9: Equal to the front end


<input type="file" name="userfile"> 

Server side $_FILES['userfile']

Line 10-36: Function triggered before file upload.

Line 11-21: Image file type filtering function, Jquery setData function used to set POST to server side values.

Line 25-26: Set whether only 1 file or multiple files are uploaded at the same time. If only 1 file is uploaded, the trigger button will be banned. To transfer several more files, set the value of MAXSIZE in the server-side PHP file uploader, although the size limit for the uploaded file also depends on the Settings in the ES142en.INI file.

Line 28~35: The text of the button is dynamically updated every 200 milliseconds during the file upload process, which has realized the effect of dynamic prompt. The window. setInterval function is used to execute the built-in function once every specified time, in milliseconds of interaction time.

Line 37-49: the function triggered after the file upload function is completed. If the server side reports an error according to the return value, the front end will prompt an error message through ALERT.

Server-side PHP file upload code

It is basically adapted from the PHP file upload function code example tutorial introduced earlier. The Settings of file upload size, error messages and other instructions have been explained in detail in this article.


$upload_dir = '../file/';
$file_path = $upload_dir . $_FILES['userfile']['name'];
$MAX_SIZE = 20000000;
echo $_POST['buttoninfo'];
if(!is_dir($upload_dir))
{
if(!mkdir($upload_dir))
echo " The file upload directory does not exist and cannot be created ";
if(!chmod($upload_dir,0755))
echo " The file upload directory permissions cannot be set to be readable or writable ";
}
if($_FILES['userfile']['size']>$MAX_SIZE)
echo " The uploaded file size exceeds the specified size ";
if($_FILES['userfile']['size'] == 0)
echo " Please select the file to upload ";
if(!move_uploaded_file( $_FILES['userfile']['tmp_name'], $file_path))
echo " Copy file failed, please reupload "; 
switch($_FILES['userfile']['error'])
{
case 0:
echo "success" ;
break;
case 1:
echo " More files have been uploaded  php.ini  In the  upload_max_filesize  Option limit value ";
break;
case 2:
echo " The size of the uploaded file is over  HTML  In the form  MAX_FILE_SIZE  The value specified by the ";
break;
case 3:
echo " Only part of the file is uploaded ";
break;
case 4:
echo " No files have been uploaded ";
break;
}

conclusion

Basically, the prototype of front-end Ajax file upload trigger function and server-side PHP file upload function has been introduced. You can supplement the front-end and front-end code according to your own needs, or you can separate 1 function independently, such as file type, single file or multi-file upload function. In general, Jquery plug-in AjaxUpload is relatively easy to implement the application of file upload function.


Related articles: