FormData没有追加文件对象

时间:2018-12-13 22:20:52

标签: javascript reactjs

我有一个在<input type="file/>的onChange事件之后执行的函数。 datazconsole.log(dataz)

之后的axios.post变量为空

const input = document.getElementById('input');

input.addEventListener('change', handlefileupload);

function handlefileupload(e) {
  var dataz = new FormData();
  dataz.append('file', e.target.files[0]);
  
  console.log(dataz);
  
  /* Note to OP: you dont need to actually include code like
     this, it has nothing to do with your question/problem
     
  axios.post('http://localhost:3000/api/v1/upload_document', {
      files: dataz
    }, {
      headers: {
        Authorization: "Bearer " + sessionStorage.getItem('loginToken'),
        'Content-Type': 'multipart/form-data'
      }
    })
    .then((response) => {
        console.log('success')

      }
    )
    .catch(function(error) {
      console.log(error.response);
    });
  */
}
<input type="file" id="input" />

这就是我的console.log(dataz)

FormData {}
__proto__: FormData
append: ƒ append()
delete: ƒ delete()
entries: ƒ entries()
forEach: ƒ forEach()
get: ƒ ()
getAll: ƒ getAll()
has: ƒ has()
keys: ƒ keys()
set: ƒ ()
values: ƒ values()
constructor: ƒ FormData()
Symbol(Symbol.iterator): ƒ entries()
Symbol(Symbol.toStringTag): "FormData"
__proto__: Object

2 个答案:

答案 0 :(得分:0)

对输入字段进行操作的事件处理程序称为“输入”。所以我怀疑你想要什么:

input.addEventListener('input', handlefileupload);

答案 1 :(得分:0)

您不能使用<a [ngClass]="{'sortList' : true }">Some link</a> 来显示console.log(dataz)值。代替此,使用以下内容:

FormData