SQLの窓 イラストAC フリー素材

2019年08月21日

一般的な PHP のアップロードページに対して jQuery の $.ajax でファイルをアップロードする

PHP における標準的なテスト用アップロードのテンプレート に対してアップロードしています。

ファイルのアップロードの PHP 側のインターフェイスに合わせてデータを用意して実行します。
PHP では、エラーの場合ページに文字列が出力されるたけなので、その文字列を検索して結果を判断します。

FileReader を使用して、選択したファイルが画像の場合は img 要素で表示し、それ以外ならば FileReader 由来のファイル名と MIME を表示します
<!DOCTYPE html>
<html>
<head>
<meta content="width=device-width initial-scale=1.0 minimum-scale=1.0 maximum-scale=1.0 user-scalable=no" name="viewport">
<title>単純ファイルアップロード</title>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.css">

<link rel="stylesheet" href="https://lightbox.sakura.ne.jp/demo/two-section.css">
<style>
#extend {
	white-space: pre;
}
</style>

<script>

$(function(){

	// ***************************
	// form 送信イベント
	// ***************************
	$("#frm").on("submit", function(event){

		// 本来の処理をキャンセル
		event.preventDefault();

		// 新規送信用オブジェクト
		var formData = new FormData();

		// テストの為、約100K の制限
		formData.append("MAX_FILE_SIZE", 1048576);

		// ファイル
		var uploadData = $("#target").get(0);

		formData.append("target", uploadData.files[0]);

		// オリジナルファイル名
		console.log( uploadData.files[0].name );

		// **************************************
		// サーバ呼び出し
		// **************************************
		$.ajax({
			url: "http://localhost/php/upload/php-upload-basic.php",
			type: "POST",
			data: formData,
			processData: false,  // jQuery がデータを処理しないよう指定
			contentType: false   // jQuery が contentType を設定しないよう指定
		})
		.done(function( data, textStatus ){
			console.log( "status:" + textStatus );

			// ajax 対応のページでは無いので、ページ上の文字列を検索して判断する
			if ( data.search(/失敗/) != -1 ) {
				alert("アップロードに失敗しました");
			}

		})
		.fail(function(jqXHR, textStatus, errorThrown ){
			console.log( "code:" + jqXHR.status );
			console.log( "status:" + textStatus );
			console.log( "errorThrown:" + errorThrown );

			// エラーメッセージを表示
			alert("システムエラーです");

		})
		.always(function() {
		})
		;

	});

	// *************************************
	// ファイル選択 <input type="file">
	// *************************************
	$("#target").on("change", function(){

		$("#extend").html("");

		var reader = new FileReader();

		reader.name = this.files[0].name;
		reader.type = this.files[0].type;
		
		console.dir(reader);

		reader.refid = "image";

		// FileReader に画像が読み込まれた時のイベント
		$(reader).on("load", function () {
		
			if ( this.type.indexOf("image/") == 0 ) {
				$("<img>").appendTo("#extend")
					.prop( {"src": this.result, "title": this.name, "id": this.refid } )	// title にはオリジナルファイル名
					.css( {"width": "100px", "margin": "10px" } );
			}
			else {
				$("<div>").appendTo("#extend")
					.html( this.name + "<br>" + this.type );
			}
			
		});

		// 上記イベントを発動するための処理( this.files[i] は blob )
		if (this.files[0]) {
			reader.readAsDataURL(this.files[0]);
		}

	});
	

});

</script>

</head>
<body>
	<div id="head">
		<form
			id="frm">
		
			<div>
				<input id="target" type="file" class="ml-4 btn btn-outline-primary">
				<input type="submit" name="send" value="アップロード" class="ml-4 btn btn-outline-primary">
				<a class="ml-4 btn btn-info" href="/php/upload/php-upload-basic.php">GET 再読み込み</a>
			</div>
		 
		</form>
	</div>

	<div id="extend">

	</div>

</body>
</html>





【jQueryの最新記事】
posted by at 2019-08-21 20:00 | jQuery | このブログの読者になる | 更新情報をチェックする