使用reactjs和ajax上传图片

时间:2016-12-31 22:32:04

标签: javascript jquery ajax reactjs

我正在尝试通过表单将图片上传到url / api。 我在提交表单时调用handleImgUpload()方法。 问题是发送的请求是空的。 我认为新的FormData(this)不适用于react或者什么。

还有另一个设置图像路径的功能。

Keys[] KeyboardInput = { Keys.A, Keys.S, Keys.N, Keys.M, Keys.H, Keys.F, Keys.T, Keys.G, 
                Keys.W, Keys.Q, Keys.Z, Keys.X, Keys.Right, Keys.Left, Keys.Up, Keys.Down };

Properties.Settings.Default.Keys = KeyboardInput;
Properties.Settings.Default.Save();

Keys[] keys = Properties.Settings.Default.Keys;

这是表格:

handleImgUpload(e){
      e.preventDefault();
      $.ajax({
        url: "my url goes here", // Url to which the request is send
        type: "POST",             // Type of request to be send, called as method
        data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
        contentType: false,       // The content type used when sending data to the server.
        cache: false,             // To unable request pages to be cached
        processData:false,        // To send DOMDocument or non processed data file it is set to false
        success: function(data){   // A function to be called if request succeeds
            console.log(new FormData(this));
        }
      });
}

1 个答案:

答案 0 :(得分:0)

this将成为React组件,而不是表单,可以在event.target

中找到
handleImgUpload(e) {
  e.preventDefault()
  let formData = new FormData(e.target)

  for (let [key, val] of d.entries()) {
    console.log(key, val) <-- should log the correct form data
  }

  // ajax stuff
}