HTML5:多文件上传 Upload multiple files at once with HTML5, jQuery and PHP

n today’s modern web applications, uploading files to the server is a very common feature, however it is often the case that your application must allow multiple file uploads to the server. Today we will build a form that will allow the user to upload multiple files to the server at once using HTML5, jQuery and PHP. Let us being …

The HTML

Nothing too fancy here, but do pay attention to the multipart attribute on the input element of type of file. This essentially tells the application to expect multiple files instead of a maximum of one.

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>File Upload in PHP</title>
		<!--[if IE]>
			<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
		<![endif]-->
		<link href="css/default.css" rel="stylesheet" type="text/css" />
		<link href="css/font-awesome.min.css" rel="stylesheet" type="text/css" />
	</head>
	<body>
		<div class="la-anim-10"></div><!-- .corner-preloader -->
		<div id="wrapper">
			<div id="upload-widget">
				<h1>
					<i class="fa fa-cloud-upload"></i> File Uploader
				</h1>

				<form id="file-upload-form">
					<div class="file-input-wrap">
						Browse Files
						<input type="file" name="file" id="file" multiple>
					</div><!-- .file-input-wrap -->
				</form><!-- #file-upload-form -->
			</div><!-- #upload-widget -->

			<div id="upload-result">
			</div><!-- #upload-result -->
		</div><!-- #wrapper -->

		<div id="preloader">
			<img src="img/preloader.gif" alt="files uploading..." />
		</div>
		
		<!-- SCRIPTS -->
		<script type="text/javascript" src="js/libraries/jquery-2.1.1.min.js"></script>
		<script type="text/javascript" src="js/custom.js"></script>
	</body>
</html>

Note also the scripts at the bottom of the html markup. You will need the jQuery library and some jQuery code which will come later. This will sit in the custom.js file.

PHP Code

Next comes the PHP code. In your favorite code editor program (I used Sublime Text 3 for this) create a new file and call it file-upload.php. In there we simply loop through the $_FILES array given to us by PHP and for each entry we do what needs to be done!

<?php
	// loop through the array of files
	foreach($_FILES as $index => $file)
	{
		// for easy access
		$fileName     = $file['name'];
		// for easy access
		$fileTempName = $file['tmp_name'];
		// check if there is an error for particular entry in array
		if(!empty($file['error'][$index]))
		{
			// some error occurred with the file in index $index
			// yield an error here
			return false;
		}

		// check whether file has temporary path and whether it indeed is an uploaded file
		if(!empty($fileTempName) && is_uploaded_file($fileTempName))
		{
			// move the file from the temporary directory to somewhere of your choosing
			move_uploaded_file($fileTempName, "uploads/" . $fileName);
			// mark-up to be passed to jQuery's success function.
			echo '<p>Click <strong><a href="uploads/'%20.%20$fileName%20.%20'" target="_blank">' . $fileName . '</a></strong> to download it.</p>';
		}
	}
?>

jQuery custom code

We will handle the submitting of the form via jQuery, we will also handle what exactly gets sent. Let us being by creating a file named custom.js and inside we will place the following code:

$(function() {
	// grab the file input and bind a change event onto it
    $('#file').bind("change", function() {
		// new html5 formdata object.
        var formData = new FormData();
        //for each entry, add to formdata to later access via $_FILES["file" + i]
        for (var i = 0, len = document.getElementById('file').files.length; i < len; i++) {
            formData.append("file" + i, document.getElementById('file').files[i]);
        }

        //send formdata to server-side
        $.ajax({
            url: "file-upload.php", // our php file
            type: 'post',
            data: formData,
            dataType: 'html', // we return html from our php file
            async: true,
            processData: false,  // tell jQuery not to process the data
            contentType: false,   // tell jQuery not to set contentType
            success : function(data) {
                $('#upload-result').append('<div class="alert alert-success"><p>File(s) uploaded successfully!</p><br />');
                $('#upload-result .alert').append(data);
            },
            error : function(request) {
                console.log(request.responseText);
            }
        });
    });
});

Note that we make use of HTML5’s FormData, so this will not work on older browsers. Always check caniuse.com for browser compatibilities.

In the HTML, ensure the referenced paths to the ‘custom.js’ file is correct. In my case, I have my custom.js file sitting inside a folder called js. I also have my ‘file-upload.php’ sitting next to my html file.

That is it! We are done. You now have a file input that can handle the upload of multiple files are once.

Note: If you are developing on your local machine and you’re using WAMP or XAMP, there are certain restrictions set in the php.ini file. These basically limit the size of the files to be uploaded and also how much time is allowed for a file to be uploaded. If you plan on uploading big files, ensure you update those settings to meet your need.

转自:http://www.code-hound.com/upload-multiple-files-at-once-with-jquery-and-php/

 

更多参考:

jQuery Filer : jQuery Html5 File Uploader 多文件上传

PHP结合HTML5使用FormData对象提交表单及上传图片

Bootstrap 3 : 图片上传预览 image upload preview

 

本文:HTML5:多文件上传 Upload multiple files at once with HTML5, jQuery and PHP

Leave a Reply