LoginSignup
6
6

More than 5 years have passed since last update.

jqueryで、formに囲まれてないtype=fileのinputのファイルを取得してajaxで送ることは可能

Last updated at Posted at 2016-02-06

jQueryで form 要素に囲われていない input[type="file"] の変更によってファイルの送信を行う際は、以下のような記述をします。

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="UTF-8">
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    <title>ファイルを送信します君</title>
  </head>
  <body>
    <div>
      <input type="file">
    </div>
    <script>(function() {
  'use strict';

  var UPLOAD_URL = 'http://example.com/upload.cgi';

  function send(file) {
    return new Promise(function(resolve, reject) {
      var req = new XMLHttpRequest();
      var body = new FormData();
      req.open('POST', UPLOAD_URL);
      req.addEventListener('load', function(event) {
        if (req.status === 200) {
          resolve(event);
        } else {
          reject(event);
        }
      });
      req.addEventListener('error', reject);
      body.append('imagedata', file);
      req.send(body);
    });
  }

  $(document).on('change', '[type="file"]', function(event) {
    event.preventDefault();
    var target = event.target;
    var file = target.files[0];
    file && send(file);
    return false;
  });
})();</script>
  </body>
</html>
6
6
1

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
6
6