簡體   English   中英

使用 formData() 上傳多個文件

[英]Uploading multiple files using formData()

var fd = new FormData();
fd.append("fileToUpload", document.getElementById('fileToUpload').files[0]);
var xhr = new XMLHttpRequest();
xhr.open("POST", "uph.php");
xhr.send(fd);

uph.php:

var_dump($_FILES['fileToUpload']);

這有效,但顯然僅適用於files[0] 如何使它適用於所選文件?

我嘗試刪除[0] ,但沒有用。

您必須獲取要附加到 JS 中的文件長度,然后通過 AJAX 請求發送,如下所示

//JavaScript 
var ins = document.getElementById('fileToUpload').files.length;
for (var x = 0; x < ins; x++) {
    fd.append("fileToUpload[]", document.getElementById('fileToUpload').files[x]);
}

//PHP
$count = count($_FILES['fileToUpload']['name']);
for ($i = 0; $i < $count; $i++) {
    echo 'Name: '.$_FILES['fileToUpload']['name'][$i].'<br/>';
}

使用javascript的方法:

var data = new FormData();

$.each($("input[type='file']")[0].files, function(i, file) {
    data.append('file', file);
});

$.ajax({
    type: 'POST',
    url: '/your/url',
    cache: false,
    contentType: false,
    processData: false,
    data : data,
    success: function(result){
        console.log(result);
    },
    error: function(err){
        console.log(err);
    }
})

如果您多次調用 data.append('file', file) 您的請求將包含您的文件數組。

來自 MDN 網絡文檔

FormData接口的append()方法將新值附加到FormData對象內的現有鍵上,如果該鍵不存在,則添加該鍵FormData.seappend()之間的區別在於,如果指定key 已經存在, FormData.set將用新值覆蓋所有現有值,而append()會將新值附加到現有值集的末尾。”

我自己使用 node.js 和 multipart handler 中間件 multer 獲取數據如下:

router.post('/trip/save', upload.array('file', 10), function(req, res){
    // Your array of files is in req.files
}

您只需要使用fileToUpload[]而不是fileToUpload

fd.append("fileToUpload[]", document.getElementById('fileToUpload').files[0]);

它將返回一個具有多個名稱、大小等的數組......

這對我有用:

let formData = new FormData()
formData.append('files', file1)
formData.append('files', file2)

這個對我有用

 //Javascript part //file_input is a file input id var formData = new FormData(); var filesLength=document.getElementById('file_input').files.length; for(var i=0;i<filesLength;i++){ formData.append("file[]", document.getElementById('file_input').files[i]); } $.ajax({ url: 'upload.php', type: 'POST', data: formData, contentType: false, cache: false, processData: false, success: function (html) { } });

 <?php //PHP part $file_names = $_FILES["file"]["name"]; for ($i = 0; $i < count($file_names); $i++) { $file_name=$file_names[$i]; $extension = end(explode(".", $file_name)); $original_file_name = pathinfo($file_name, PATHINFO_FILENAME); $file_url = $original_file_name . "-" . date("YmdHis") . "." . $extension; move_uploaded_file($_FILES["file"]["tmp_name"][$i], $absolute_destination . $file_url); }

在附加到 fd 時添加[]有效,但是如果您希望將數據按文件分組,那么我建議您這樣做:

var files= document.getElementById('inpFile').files
var fd = new FormData()

for (let i = 0; i < files.length; i++) {
  fd.append(i, files[i])
}

現在您的數據將按文件分組發送,而不是按屬性分組。

這很好用!

var fd = new FormData();

$('input[type="file"]').on('change', function (e) {
    [].forEach.call(this.files, function (file) {
        fd.append('filename[]', file);
    });
});

$.ajax({
    url: '/url/to/post/on',
    method: 'post',
    data: fd,
    contentType: false,
    processData: false,
    success: function (response) {
        console.log(response)
    },
    error: function (err) {
        console.log(err);
    }
});

這對我有用

var ins = $('.file').map(function () {
    return this.files;
}).get();

for (var x = 0; x < ins; x++) {
    formData.append("file", ins[x][0]);
}

我的工作是這樣的:

var images = document.getElementById('fileupload').files;
var formData = new FormData();
for(i=0; i<images.length; i++) {
     formData.append('files', images[i]);
}

如果我們在 html 中有輸入:

<input id="my-input" type="file" mutliple /> // multiple attribute to select and upload multiple files

我們可以從該輸入中獲取文件並使用純 js 腳本將其發送到服務器:

const myInput = document.getElementById('my-input') // getting our input

myInput.addEventListener('change', (event) => { // listening for file uploads
    const files = event.target.files // getting our files after upload
    const formData = new FormData() // create formData

    for (const file of files) {
        formData.append('files', file) // appending every file to formdata
    }

    const URL = 'http://server.com:3000'
    const response = fetch(URL, {
       method: 'POST',
       data: formData // sending our formdata in body of post request
    })

    return response.json() 
}

它對我來說很完美

PS:我在后端使用multer (node.js + express),添加到文件上傳路由

upload.array("files", 10)
  • 第一個參數是我們文件的屬性名稱(在 formdata 中)
  • 第二個參數是最大文件大小

我為我找到了這份工作!

var fd = new FormData();
$.each($('.modal-banner [type=file]'), function(index, file) {
  fd.append('item[]', $('input[type=file]')[index].files[0]);
});

$.ajax({
  type: 'POST',
  url: 'your/path/', 
  data: fd,
  dataType: 'json',
  contentType: false,
  processData: false,
  cache: false,
  success: function (response) {
    console.log(response);
  },
  error: function(err){
    console.log(err);
  }
}).done(function() {
  // do something....
});
return false;

要上傳帶有角度表單數據的多個文件,請確保您的 component.html 中有此文件

上傳文件

                <div class="row">


                  <div class="col-md-4">
                     &nbsp; <small class="text-center">  Driver  Photo</small>
                    <div class="form-group">
                      <input  (change)="onFileSelected($event, 'profilepic')"  type="file" class="form-control" >
                    </div>
                  </div>

                  <div class="col-md-4">
                     &nbsp; <small> Driver ID</small>
                    <div class="form-group">
                      <input  (change)="onFileSelected($event, 'id')"  type="file" class="form-control" >
                    </div>
                  </div>

                  <div class="col-md-4">
                    &nbsp; <small>Driving Permit</small>
                    <div class="form-group">
                      <input type="file"  (change)="onFileSelected($event, 'drivingpermit')" class="form-control"  />
                    </div>
                  </div>
                </div>



                <div class="row">
                    <div class="col-md-6">
                       &nbsp; <small>Car Registration</small>
                      <div class="form-group">
                        <div class="input-group mb-4">
                            <input class="form-control" 
                (change)="onFileSelected($event, 'carregistration')" type="file"> <br>
                        </div>
                      </div>
                    </div>

                    <div class="col-md-6">
                        <small id="li"> Car Insurance</small>
                      <div class="form-group">
                        <div class="input-group mb-4">
                          <input class="form-control" (change)="onFileSelected($event, 

                         'insurancedocs')"   type="file">
                        </div>
                      </div>
                    </div>

                  </div>


                <div style="align-items:c" class="modal-footer">
                    <button type="button" class="btn btn-secondary" data- 
                  dismiss="modal">Close</button>
                    <button class="btn btn-primary"  (click)="uploadFiles()">Upload 
                  Files</button>
                  </div>
              </form>

在您的 componenet.ts 文件中聲明數組選擇的文件,如下所示

selectedFiles = [];

// 選定文件的數組

onFileSelected(event, type) {
    this.selectedFiles.push({ type, file: event.target.files[0] });
  }

//在上傳文件方法中,像這樣附加您的表單數據

uploadFiles() {
    const formData = new FormData(); 

    this.selectedFiles.forEach(file => {
      formData.append(file.type, file.file, file.file.name); 
    });
    formData.append("driverid", this.driverid);

    this.driverService.uploadDriverDetails(formData).subscribe(
      res => {
        console.log(res); 

      },
      error => console.log(error.message)
    );
  }

注意:我希望這個解決方案對你的朋友有用

如果您正在實例化已經將表單作為構造函數參數傳遞的 FormData 對象,則輸入文件的名稱屬性必須包含方括號。

HTML:

<form id="myForm" method="POST" action="url" enctype="multipart/form-data">
<input class="form-control form-control-lg" type="file" name="photos[]" multiple />

JS:

var formData = new FormData(document.getElementById('myForm'));
console.log(formData.getAll('photos[]'));

這對我有用!

這對我也有用:

var data  = new FormData();
for (const key in files)
    data.append('gallery[]',files[key])

這是針對此問題的Vanilla JavaScript解決方案 -

首先,我們將使用Array.prototype.forEach()方法,如

document.querySelectorAll('input[type=file]')返回一個類似 object 的數組

然后我們將使用Function.prototype.call()方法將類數組對象中的每個元素分配給.forEach方法中的this值。

HTML

<form id="myForm">

    <input type="file" name="myFile" id="myFile_1">
    <input type="file" name="myFile" id="myFile_2">
    <input type="file" name="myFile" id="myFile_3">

    <button type="button" onclick="saveData()">Save</button>

</form>

JavaScript

 function saveData(){
     var data = new FormData(document.getElementById("myForm"));
     var inputs = document.querySelectorAll('input[type=file]');

     Array.prototype.forEach.call(inputs[0].files, function(index){
        data.append('files', index);
     });
     console.log(data.getAll("myFile"));
}

您可以在此處查看相同的工作示例

創建一個FormData對象

const formData: any = new FormData();

並附加到相同的 keyName

photos.forEach((_photoInfo: { localUri: string, file: File }) => {
    formData.append("file", _photoInfo.file);
});

並將其發送到服務器

// angular code
this.http.post(url, formData)

這將自動在file下創建一個對象數組

如果您使用的是 nodejs

const files :File[] = req.files ? req.files.file : null;
let fd = new FormData();
fd.append( "images" , image1 );
fd.append( "images" , image2 );
fd.append( "images" , image3 );

在這種格式下,您可以通過 axios 發送多個文件。但我對此遇到了一些問題。 當我嘗試在表單數據中發送 append 並嘗試通過 axios 發送此文件時,只上傳了一個文件。我的問題是我從“axios”導入了 {Axios},但它不會工作。 我們必須從“axios”導入 axios(查看拼寫),然后它對我來說很完美

const files: FileList = e.target.files;
const formData = new FormData()
for(let i =o; i < files.length; i++) {
 formData.append('files', files[i], file[i].name);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM