file的ajax,Ajax File Upload

宫坚
2023-12-01

OpenJS > Articles > Ajax File Upload

Ajax File Upload

You might have seen Ajax File Uploading in some sites. The basic idea is to upload a file without refreshing the page. Some sites go even further by providing details on how much percentage is uploaded, etc. It is very easy to achieve this effect using javascript.

First off, I did not like using the term 'Ajax' when describing this method. But there is no other word that can be used. And this method fits within my definition of Ajax - "Sending or receiving data from the server without refreshing the page.". So I will name this method Ajax file upload.

Theory

The basic idea behind this effect is to redirect a form's action into a hidden IFrame. So, when the form with the file field is submitted, the result will appear in a IFrame. But since it is hidden, the user will not see it. This effect is achieved using the 'target' attribute of the Form tag.

See the small squire? That is the IFrame. Typically, it will be hidden.

Code

(X)HTML

JavaScript

function init() {

document.getElementById('file_upload_form').οnsubmit=function() {

document.getElementById('file_upload_form').target = 'upload_target'; //'upload_target' is the name of the iframe

}

}

window.οnlοad=init;

PHP

This should be in upload.php - the action of the form.

include('../../../common.php');

upload('file','.','txt,jpg,jpeg,gif,png');

The code to upload the file must be given here. I used one of my custom functions to upload the file - it is not a native PHP function. Needless to say, this is not restricted to PHP - you can use any server side language here.

blog comments powered by Disqus

 类似资料: