LoginSignup
1
1

More than 5 years have passed since last update.

form.ajaxSubmit() でアップロード

Last updated at Posted at 2015-06-25

概要

  • form.ajaxSubmit() で画面遷移なしにアップロード
  • ファイル選択をすると即アップロード
  • アップロード受付側はなんでもいい

コード

HTML

index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title></title>
  <script src="//code.jquery.com/jquery-2.1.4.min.js"></script>
  <script src="//malsup.github.com/jquery.form.js"></script>
  <script src="script.js"></script>
</head>
<body>
  <form action="upload.php" method="POST" id="form" enctype="multipart/form-data">
    <input id="file" type="file" name="myfile" accept="image/png">
  </form>
</body>
</html>

PHP (アップロード待ち受け)

PHP マニュアルページからコピペ。必要最小限のアップロード待ち受け処理

upload.php
<?php
// In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
// of $_FILES.

$uploaddir = 'uploads/';
$uploadfile = $uploaddir . basename($_FILES['myfile']['name']);

if (move_uploaded_file($_FILES['myfile']['tmp_name'], $uploadfile)) {
    echo "File is valid, and was successfully uploaded.\n";
} else {
    echo "Possible file upload attack!\n";
}

// echo 'Here is some more debugging info:';
// print_r($_FILES);

jQuery

script.js
$(document).ready(function () {
  $('#file').on('change', function () {
    $('#form').submit();
  });

  $('#form').on('submit', function (e) {
    e.preventDefault();
    $(this).ajaxSubmit();
  });
});

試してみる

  • ビルトインサーバ(php -S localhost:3000)を利用して接続を待ち受けさせる
  • localhost:3000/index.html にアクセス
  • アップロードするファイルを選択

Links

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1