14
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ajax(jQuery)でファイルをアップロードする

Last updated at Posted at 2019-04-18

同じような記事はかなりありますが、よく忘れるのでメモ。

#ajaxでファイルのアップロード

<form>
    <input type="file" name="upfile">
    <button id="upButton" type="button">送信</button>
</form>
let $upfile = $('input[name="upfile"]');
let fd = new FormData();
fd.append("upfile", $upfile.prop('files')[0]);

$('#upButton').on('click', function () {
    $.ajax({
        url:'index.php',
        type:'post',
        data: fd,
        processData: false,
        contentType: false,
        cache: false,
    }).done(function (data) {
        // 成功時の処理
    }).fail(function() {
       // 失敗時の処理
    });
});
index.php
$upfile = $_FILES['file'];

#formの中身をまとめて送信

<form>
    <input type="file" name="upfile">
    <input type="text" name="foo" value="bar">
    <input type="hidden" name="hoge" value="fuga">
    <button id="upButton" type="button">送信</button>
</form>
let $form = $('form');
let fd = new FormData($form.get(0));

$('#upButton').on('click', function () {
    $.ajax({
        url:'index.php',
        type:'post',
        data: fd,
        processData: false,
        contentType: false,
        cache: false,
    }).done(function (data) {
        // 成功時の処理
    }).fail(function() {
       // 失敗時の処理
    });
});
index.php
$upfile = $_FILES['upfile'];
$foo = $_POST['foo'];
$bar = $_POST['hoge'];

#参考URL
JavaScript(jQuery)からPHPのAPIを利用する
https://qiita.com/mpyw/items/62e6e415f86eb30a5ff4

[JavaScript] Ajaxでファイルをアップロード【jQuery使用】
https://qiita.com/yasumodev/items/cffb735f46ffd489a4db

ajaxでファイルをアップロードする方法(メモ)
https://qiita.com/BRS_matsuoka/items/ba79a2f500a10ddc0923

Ajaxを用いてテキストと画像ファイルを投稿する
https://qiita.com/sho012b/items/f2558db5dad97d7e1b1d

14
16
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
14
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?