简体   繁体   English

使用ajax表单提交发送文件数据

[英]Sending file data with ajax form submit

I have got issue sending file to a server with ajax for submitting. 我在将文件发送到具有ajax的服务器进行提交时遇到问题。 I tried lots of methods with var xhr = new XMLHttpRequest(); 我用var xhr = new XMLHttpRequest();尝试了很多方法var xhr = new XMLHttpRequest(); and $.ajax({}); $.ajax({}); but always its gives error Uncaught TypeError: Illegal invocation . 但始终会给出错误Uncaught TypeError: Illegal invocation I also use processData: false , but in this condition I got all form fields apart file field. 我也使用processData: false ,但是在这种情况下,我得到了所有表单字段和文件字段。

My Code for ajax is: 我对ajax的代码是:

var fd = new FormData();
fd.append( 'file', $('#file')[0].files[0] );
fd.append( 'name', 'test');
$.ajax({
    url: "uploadFile.php",
    data: fd,
    cache: false,
    contentType: false,
    // processData: false,
    type: 'POST',
    success: function(data, textStatus, jqXHR){
        console.log('success');
    },
    error: function(jqXHR, textStatus, errorThrown){
        console.log('error');
    }
});

In this I got only name field with value test in output, but not file . 在这种情况下,我仅在输出中获得nametest name字段,而没有file Somebody please let me know where I am wrong. 有人请让我知道我错了。

Set contentType to specific format instead of false. 将contentType设置为特定格式,而不是false。 For eg. 例如。 in case of image set it to :- "image/jpeg" etc. 如果是图片,请将其设置为:-“ image / jpeg”等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM