How to get content from formData?

I created a file in the form of a Date like this:

    var fd = new FormData();
    fd.append('file', file);    

How to get content from a form? how is the file name and file? something like this: fd.filename(), fd.getData(). or fd.get('file')to return a file?

+4
source share
5 answers

Cannot retrieve files after you add them to the formData object.

You will need to send the formData object somewhere, and then get the files from the req object or something like that.

In my case (angularJS + nodeJS) I checked this from the answer to SO (link below):

Angular:

var fd = new FormData();
fd.append('file', file);
$http({
  method:"POST",
  url:"uploadFile",
  data: fd,
  withCredentials: true,
  headers: {'Content-Type': undefined },
  transformRequest: angular.identity
});

Node (expressJS):

app.post('/uploadFile', function(req,res){
  fs.readFile(req.files.file.path, function(err, data){
    // Do something with the data (which holds the file information)
  });
});

To find out what you can do with the file, read the following: http://nodejs.org/api/fs.html

: AngularJS: ?

+2

filedata . .

var files=document.getElementById('fileID').files[0];

formdata ajax;

fd.append('file',files);

: enctype multipart/formdata​​p >

+1

Try:

 var fd = new FormData();
 fd.append('file', file); 

:

   var newfile = fd.get('file');
      console.log(newfile.name);       //filename
      console.log(newfile.size);       //filesize

:

 for (var newfile of fd.getAll('file')){
     console.log(newfile.name);
     console.log(newfile.size);
}  

FormData:

var newFormData = new FormData();
    newFormData.append('file', newfile);

FormData, , FormData.entries():

for (var pair of fd.entries())
    {
     console.log(pair[0]+ ', '+ pair[1]);   //property and value pairs
    }
+1

Mozilla , , FormData. FormData AJAX.

: , FormData:

var myFormData = {
    key1: 300,
    key2: 'hello world'
};

var fd = new FormData();
for (var key in myFormData) {
    console.log(key, myFormData[key]);
    fd.append(key, myFormData[key]);
}

FormData, , :

var xhr = new XMLHttpRequest;
xhr.open('POST', '/', true);
xhr.send(fd);

FormData POST . JS Bin, , FormData, .

0

Source: https://habr.com/ru/post/1531756/


All Articles