Home Web Front-end JS Tutorial jQuery Ajax file upload (php)_jquery

jQuery Ajax file upload (php)_jquery

May 16, 2016 pm 06:51 PM
ajax jquery File Upload

How to implement jQuery's Ajax file upload, PHP faithful file upload.
AJAX upload file, PHP upload file.

【PHP file upload】

Before we begin, I think it is necessary to briefly explain the principle of uploading files through the WEB.
Actually, whether it is PHP, JSP, or ASP that processes the uploaded files here, the WEB has already uploaded the files to the server. We just use the upload processing function to process the uploaded files.
The processing functions are generally implemented using server-side languages ​​such as PHP, JSP, and ASP. So how to upload files through WEB (HTTP protocol?) You need HTML code similar to the following:
test.html

Copy code The code is as follows:


Pictures:




Note: enctype="multipart/form-data" is required. It tells the FORM table that this is a file upload type. Once the request is successful, the file will be uploaded to the temporary folder of the server.
As for how the file will be processed after arriving at the destination, it is a matter of PHP, JSP, and ASP.
(However, don’t be too happy too early. If the file is not moved to other places or renamed, the file will be deleted at the end of the form request. So we have to write a script to handle uploaded files)
Here we use PHP to handle it
do_file_upload.php

Copy code The code is as follows:

$error = "" ; //Upload file error message
$msg = "";
$fileElementName = 'picture';
$allowType = array(".jpg",".gif",".png"); //File types allowed to be uploaded
$num = strrpos($_FILES['picture']['name'],'.');
$fileSuffixName = substr($_FILES['picture'][' name'],$num,8);//This number is variable
$fileSuffixName = strtolower($fileSuffixName); //Determine the type of uploaded file

$upFilePath = 'd:/'; //Final storage path

if(!empty($_FILES[$fileElementName]['error']))
{
switch($_FILES[$fileElementName]['error'])
{

case '1':
$error = 'The transferred file exceeds the limit of the upload_max_filesize option in php.ini';
break;
case '2':
$error = 'The size of the uploaded file exceeds the value specified by the MAX_FILE_SIZE option in the HTML form';
break;
case '3':
$error = 'Only part of the file was uploaded';
break;
case '4':
$error = 'No file uploaded';
break;

case '6':
$error = 'Temp folder not found';
break;
case '7':
$error = 'File writing failed';
break;
default:
$error = 'Unknown error';
}
}elseif(empty($_FILES['fileToUpload']['tmp_name']) || $_FILES[ 'fileToUpload']['tmp_name'] == 'none')
{
$error = 'No file uploaded.';
}else if(!in_array($fileSuffixName,$allowType))
{
$error = 'File type not allowed to upload';
}else{
);
if($ok === FALSE){
$error = 'Upload Failed';
}
}
?>

Another note: About the $_FILES array

This array contains all uploaded file information, which records the relevant information when uploading files.
The contents of the $_FILES array in the above example are as follows. Let's assume that the name of the file upload field is userfile as shown in the example above. The name can be whatever you want.

$_FILES['userfile']['name']
The original name of the client machine file.

$_FILES['userfile']['type']
The MIME type of the file, if the browser provides this information. An example is "image/gif". However, this MIME type is not checked on the PHP side, so don't take it for granted.

$_FILES['userfile']['size']
The size of the uploaded file, in bytes.

$_FILES['userfile']['tmp_name']
The temporary file name stored on the server after the file is uploaded.

$_FILES['userfile']['error']
Error code related to the file upload. This project was added in PHP version 4.2.0.

【AJAX file upload】

In fact, it is to achieve refresh-free file upload. The IFRAME file upload principle can be used.
Actually when uploading files with PHP. . . Only the $_FILES format can be used, but if we just use JS to get its ID, such as ..document.getElementById('img').value or jquery $("#img") in the form cannot be actually uploaded (but there are still many people doing this, including me at the beginning).
But the function also requires the implementation of the so-called "asynchronous upload", what should I do? ? You can only use third-party components, or write one yourself (embed an IFRAME in the web page). But if you are considering development time, you can use a third party. Here is a good jQuery Ajax file upload component, which is "ajaxfileupload.js". Its component download address is: http://www.phpletter.com/ , there is a PHP application demo inside after downloading, which is easy to understand.
Process:
(1) Code of the file on the front end: test.php

Copy code The code is as follows:

   
   
   

相应的HTML为:

复制代码 代码如下:

       
       

这样客户端就完成了。

(2) 再服务器端时   doajaxfileupload.php

   此处为了简便的检测是否真正的传值过来了,你可以将它存起来了。
             $file_infor = var_export($_FILES,true);
             file_put_contents("d:file_infor.php".$file_infor);
   这样你打来刚生成的file_infor.php文件时,你又看到了熟悉的信息了:

复制代码 代码如下:

array(
'name'=>'lamp.jpg',
'type'=>'image/pjpeg',
'tmp_name'=>'c: windowstempphpFA.tmp',
'error'=>0,
'size'=>3127
)


Of course, the real processing is similar to this of:

Copy code The code is as follows:

$upFilePath = "d:/";
);
if($ok === FALSE){
echo json_encode('file_infor'=>'Upload failed');
}else {
echo json_encode('file_infor'=>'Upload successful');
}
?>


Another note: Actually, you can Embed an IFRAME in a page, and then submit it using the native POST form in the IFRAME. This JQUERY plug-in also uses this method. It’s just that it is a dynamically generated IFRAME and form

Original text: http://fc-lamp.blog.163.com/blog/static/1745666872009519310153/
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use gRPC to implement file upload in Golang? How to use gRPC to implement file upload in Golang? Jun 03, 2024 pm 04:54 PM

How to implement file upload using gRPC? Create supporting service definitions, including request and response messages. On the client, the file to be uploaded is opened and split into chunks, then streamed to the server via a gRPC stream. On the server side, file chunks are received and stored into a file. The server sends a response after the file upload is completed to indicate whether the upload was successful.

Simplify file upload processing with Golang functions Simplify file upload processing with Golang functions May 02, 2024 pm 06:45 PM

Answer: Yes, Golang provides functions that simplify file upload processing. Details: The MultipartFile type provides access to file metadata and content. The FormFile function gets a specific file from the form request. The ParseForm and ParseMultipartForm functions are used to parse form data and multipart form data. Using these functions simplifies the file processing process and allows developers to focus on business logic.

How to use PUT request method in jQuery? How to use PUT request method in jQuery? Feb 28, 2024 pm 03:12 PM

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

How to implement drag and drop file upload in Golang? How to implement drag and drop file upload in Golang? Jun 05, 2024 pm 12:48 PM

How to implement drag and drop file upload in Golang? Enable middleware; handle file upload requests; create HTML code for the drag and drop area; add JavaScript code for handling drag and drop events.

How to get variables from PHP method using Ajax? How to get variables from PHP method using Ajax? Mar 09, 2024 pm 05:36 PM

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

jQuery Tips: Quickly modify the text of all a tags on the page jQuery Tips: Quickly modify the text of all a tags on the page Feb 28, 2024 pm 09:06 PM

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: &lt

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

Use jQuery to modify the text content of all a tags Use jQuery to modify the text content of all a tags Feb 28, 2024 pm 05:42 PM

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on ​​the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

See all articles