与我使用CURL一样,如何使用AJAX发布文件

时间:2018-06-23 18:03:37

标签: javascript ajax apache curl solr

我正在运行这些命令,以将PDF和JSON文件发送到Apache SOLR。当我在终端中使用cURL时,这非常完美。

PDF文件:

curl -X POST -H "Content-Type:application/pdf" "http://localhost:8983/solr/pdf_core_sample/update/extract?literal.filename=pdfsample"
--data-binary @files/pdf_sample.pdf

JSON文件:

curl -X POST -H "Content-Type:application/json" "http://localhost:8983/solr/pdf_core_sample/update?commit=true" --data-binary @files/simple_1.json

但是我想创建一个简单的Web应用程序,以使用UI将文件上传/发送到Apache Solr。

这是代码:

HTML:

<div>
  <h3>Upload file</h3>
  <form id="file_index_form">
    <input id="file_input" type="file">
    <button id="upload_btn">Upload</button>
  </form>
</div>

JAVASCRIPT:

$(document).ready(function() {

            $("#file_index_form").submit((e) => {

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

                var upload_file = document.getElementById("file_input").files[0];
                var file_name = upload_file.name;
                var file_type = upload_file.type;
                var solr_port = 8983;
                var solr_core = "pdf_core_sample";
                var solr_url = "http://localhost:"+solr_port+"/solr/"+solr_core;

                // Create the data object
                var data = new FormData();

                // Create the URL
                if(file_type === "application/json") {

                    solr_url = encodeURI(solr_url+="/update?commit=true");

                } else if(file_type === "application/pdf") {

                    solr_url = encodeURI(solr_url+="/update/extract?literal.filename="+file_name);

                }

                $.ajax({
                    url: solr_url,
                    type: 'POST',
                    data: data,
                    contentType: file_type,
                    processData: false,
                    cache: false,
                    success: function(data)
                    {
                        console.log("Success");
                    },
                    error: function(jqXHR, textStatus, errorThrown)
                    {
                        console.log('ERRORS: ' + textStatus);
                    }
                });

            });
    });

我收到此错误:http://prntscr.com/jyhh01

0 个答案:

没有答案