如何使用Grails webservice通过jQuery Ajax上传图像

时间:2015-01-15 10:06:08

标签: jquery ajax grails

我有一个web服务来上传通过GRAILS实现的文件。 我可以使用以下命令使用CURL来使用Web服务:

curl -X POST -H "Authorization: 53676c55f8014c5eb84624b49d9c9e74" -H "Content-Type: multipart/form-data" http://localhost:8080/project/api/profiles/11/uploadlogo -F "img=@c:/my_image.jpg"

如何使用jQuery AJAX函数来使用它?

我确实喜欢这样,但它没有用:

var files = [];

$('input').change(function(e){            
    files = e.target.files;    
});

$('form').on('submit', function(e){

  e.stopPropagation();
  e.preventDefault();

  var data = new FormData();
  $.each(files, function(i, file) {
     console.log(file)
     data.append('img', $('input').val());
  });

  $.ajax({
    url: 'http://localhost:8080/hsp-main/api/profiles/11/uploadimage',
    contentType: 'false',
    type: 'post',
    processData: false,
    header: {
      "Authorization": '88db1ec45c3f4882859d59df45900fd5'
    },
    data: data
    }).done(function(response){
      console.log(response);
    }).fail(function(a, s, d){
      console.log(a, s, d);
    });

     return false;
});

1 个答案:

答案 0 :(得分:0)

这是解决方案

            var data = new FormData();
            data.append("img", $('input[type="file"]')[0].files[0]);

            $.ajax({
                url: 'http://64.15.146.86:9090/hsp-main-0.1/api/profiles/11/uploadimage',
                cache:false,
                processData:false,
                contentType:false,
                type:'POST',
                success:function (data, status, req) {
                    console.log(req);
                },
                error:function (req, status, error) {
                    console.log(req);
                },
                headers: {
                    'Authorization': 'ec5ce080a64941c68a84cac8f28293dd'
                },
                data: data
            }).done(function(response){
                console.log(response);
            }).fail(function(a, s, d){
                console.log(a, s, d);
            });