简体   繁体   English

使用Jquery / Ajax将文件上传到本地REST服务

[英]Upload file using Jquery/Ajax to local REST service

I want to upload files to our DB through my REST service using the file explorer, as of now I manage to open the file explorer by clicking my findDocumentOnboarding button of input type="file" . 我想使用文件浏览器通过REST服务将文件上传到我们的数据库,到目前为止,我设法通过单击input type="file" findDocumentOnboarding按钮来打开文件浏览器。 But I have not managed to upload the selected file using my uploadDocumentOnboarding button. 但是我没有使用我的uploadDocumentOnboarding按钮上传所选文件。

I have tried using the following code: 我尝试使用以下代码:

HTML : HTML

<input type="button" value="Upload document" class="btn btn-xs btn-primary uploadDocumentOnboarding">
<input id="file" type="file" class="findDocumentOnboarding">

Jquery/Javascript : jQuery / Javascript

    $(".uploadDocumentOnboarding").on(click, function (evt) {
    IdToEdit = $(this).closest('tr').siblings().find('p.important').text();
    alert(IdToEdit);
    var url = "http://localhost:10110/MavenProject/api123/Onboard/uploads/"+IdToEdit;
    evt.preventDefault();

    var documentData = new FormData();
    documentData.append("file", $('input#file.findDocumentOnboarding')[0].files[0]);
    $.ajax({
        url: url,
        type: 'PUT',
        data: {'testBlob': (documentData)},
        async: false,
        cache: false,
        contentType: false,
        enctype: 'multipart/form-data',
        processData: false,
        success: function (response) {
            alert(response);
        }
    });

    return false;
});

What am I doing wrong here? 我在这里做错了什么?

Any help is greatly appreciated! 任何帮助是极大的赞赏!

Edit : I'm now getting PUT 415 Unsupported Media Type 编辑 :我现在正在获取PUT 415 Unsupported Media Type

尝试用.on("click"代替.on(click ;删除async: false, ,, enctype: 'multipart/form-data',

I had to do it like this, notice the POST instead of PUT and the data and appended data difference: 我必须这样做,注意POST而不是PUT和数据以及附加数据的区别:

    $(".uploadDocumentOnboarding").on("click", function (evt) {
    IdToEdit = $(this).closest('tr').siblings().find('p.important').text();
    var url = "http://localhost:10110/MavenProject/api123/Onboard/uploads/"+IdToEdit;
    evt.preventDefault();

    var documentData = new FormData();
    documentData.append('file', $('input#file.findDocumentOnboarding')[0].files[0]);
    $.ajax({
        url: url,
        type: 'POST',
        data: documentData,
        cache: false,
        contentType: false,
        processData: false,
        success: function (response) {
            alert("Document uploaded successfully.");
        }
    });

    return false;
});

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

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