简体   繁体   English

使用jQuery使用multipart / form-data进行HTTP POST调用?

[英]Making an HTTP POST call with multipart/form-data using jQuery?

I'm trying to make a HTTP POST call with multipart/form-data , using jQuery: 我正在尝试使用jQuery使用multipart / form-data进行HTTP POST调用:

$.ajax({
  url: 'http://localhost:8080/dcs/rest',
  type: 'POST',
  contentType:'multipart/form-data',
  data: 'dcs.source=boss-web&query=data&dcs.algorithm=lingo&dcs.output.format=JSON&dcs.clusters.only=true', 
  //dataType: "jsonP",
  success: function(jsonData) {alert('POST alert'); data=jsonData ; },
  error : function(XMLHttpRequest, textStatus, errorThrown) {
            console.log('An Ajax error was thrown.');
            console.log(XMLHttpRequest);
            console.log(textStatus);
            console.log(errorThrown);
          }
});

It doesn't work. 它不起作用。 Firebug returns an undefined error and the returned XMLHttpRequst object multipart field is set to false. Firebug返回未定义的错误,返回的XMLHttpRequst对象multipart字段设置为false。

What can i do to make this work with jQuery? 我可以做些什么来使用jQuery工作? And if it's not possible is there a simple to achieve this? 如果不可能有一个简单的实现这个?

ie idon't need to transfer files , just some data. 即idon't不需要传输文件,只需要一些数据。 but the server requires multipart. 但服务器需要multipart。

multipart/form-data doesn't look at like this: multipart/form-data看起来不像这样:

dcs.source=boss-web&query=data&dcs.algorithm=lingo&dcs.output.format=JSON&dcs.clusters.only=true

This is application/x-www-form-urlencoded . 这是application/x-www-form-urlencoded

Here's an example of how multipart/form-data request looks like. 以下是multipart/form-data请求的示例 And the related RFC 1867 . 和相关的RFC 1867

multipart/form-data is quite often associated with uploading files. multipart/form-data经常与上传文件相关联。 If this is your case you could take a look at the jquery form plugin which allows you to ajaxify forms and supports file uploads as well. 如果是这种情况,您可以查看jquery表单插件 ,它允许您ajaxify表单并支持文件上传

Using FormData(), you can upload files via ajax request. 使用FormData(),您可以通过ajax请求上传文件。

Refer this link for more info: FormData 有关详细信息,请参阅此链接: FormData

Tutorial about using FormData: tutorial 关于使用FormData的教程教程

This way works: 这种方式有效:

$( "form#upload-form" )
    .attr( "enctype", "multipart/form-data" )
    .attr( "encoding", "multipart/form-data" );
$.ajax({ 
    type: "POST",
    contentType:attr( "enctype", "multipart/form-data" ),
    url: "/adm/oferta_insert",
    data: dados, 
    success: function( data ) { 
        alert( data );  
    }  
});  

http://www.bennadel.com/blog/1273-Setting-Form-EncType-Dynamically-To-Multipart-Form-Data-In-IE-Internet-Explorer-.htm http://www.bennadel.com/blog/1273-Setting-Form-EncType-Dynamically-To-Multipart-Form-Data-In-IE-Internet-Explorer-.htm

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

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