ajax を使ってファイルのアップロード
jQuery の ajax を使ったファイルのアップロードです。
サーバーサイドは、PHP です。
upload_ajax.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta http-equiv="CONTENT-TYPE" content="text/html; charset=utf-8" />
<script src="/js/jquery-3.6.0.min.js"></script>
<script src="upload_ajax.js"></script>
<title>upload ajax</title>
</head>
<body>
<h2>upload ajax</h2>
<form id="foo">
<input id="file" name="file" type="file" />
<input id="send" type="submit" />
</form>
<br />
<div id="result"></div>
<br />
<hr />
<div id="outarea_aa">outarea_aa</div>
<div id="outarea_bb">outarea_bb</div>
<div id="outarea_cc">outarea_cc</div>
<div id="outarea_dd">outarea_dd</div>
<div id="outarea_ee">outarea_ee</div>
<div id="outarea_ff">outarea_ff</div>
<div id="outarea_gg">outarea_gg</div>
<div id="outarea_hh">outarea_hh</div>
<hr />
Apr/12/2021<p />
</body>
</html>
upload_ajax.js
// ---------------------------------------------------------------
// upload_ajax.js
//
// Apr/12/2021
//
// ---------------------------------------------------------------
jQuery(function ()
{
jQuery('#foo').submit(function(){
var fd = new FormData(jQuery('#foo').get(0))
jQuery.ajax({
url: "upload_ajax.php",
type: "POST",
data: fd,
processData: false,
contentType: false,
dataType: 'json'
})
.done(function( data ) {
var str_out = ""
for (it in data.message)
{
str_out += data.message[it] + "<br />"
}
jQuery('#result').html(str_out)
jQuery('#outarea_cc').text(JSON.stringify (data))
})
return false
})
})
//
// ---------------------------------------------------------------
upload_ajax.php
<?php
// ------------------------------------------------------------------
// upload_ajax.php
//
// Apr/12/2021
//
// ------------------------------------------------------------------
if ($_FILES['file']) {
$size = getimagesize( $_FILES['file']['tmp_name'] );
$data = array ();
$data = array( 'width' => $size[0], 'height' => $size[1] );
$filename = $_FILES['file']['name'];
$tmp_name = $_FILES['file']['tmp_name'];
$data['filename'] = $filename;
$data['tmp_name'] = $tmp_name;
$message = array ();
$message[] = "*** check ***";
$path_target = "./data_work/" . $filename;
$message[] = $path_target;
if (move_uploaded_file ($tmp_name,$path_target) == FALSE)
{
$message[] = 'nothing is uploaded at ' . $_POST['now'];
$message[] = $filename . " cannot be uploaded.";
}
else
{
$message[] = "*** success ***";
$message[] = $filename . " is uploaded.";
}
$data['message'] = $message;
header('Content-type: text/html');
echo json_encode($data);
}
// ------------------------------------------------------------------
?>
Author And Source
この問題について(ajax を使ってファイルのアップロード), 我々は、より多くの情報をここで見つけました https://qiita.com/ekzemplaro/items/95ea5eef39854cbc348c著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .