【问题标题】:Upload and Display Images using HTML, JS and MONGODB使用 HTML、JS 和 MONGODB 上传和显示图像
【发布时间】:2017-08-05 16:30:47
【问题描述】:

我已设法使用 HTML 和 JS 在我的页面上加载图像,但我似乎无法将图像发布到我的 MongoDB 并且它不会显示在我的“主页”页面上。

HTML:

<div class="container">
    <h1 style="text-align: center">Post a New Guitar</h1>
    <div class="col-md-6">
        <form action="/guitars" method="POST">
        <div class="input-group">
            <label>Item Name</label>
            <div class="input-group">
                <input class="form-control" type="text" name="name" placeholder="Name">
            </div>
            <label>Upload Image</label>
            <div class="input-group">
        <span class="input-group-btn">
            <span class="btn btn-default btn-file">
                Browse… <input type="file" id="imgInp">
            </span>
        </span>
        <input type="text" class="form-control" readonly>
    </div>
    <img id="img-upload"/>

      <div class="input-group">
            <button class="btn btn-lg btn-primary btn-block">Submit!</button>
        </div>

    <a href="/guitars">Go Back</a>
</div>

JS:

        $(document).ready( function() {
            $(document).on('change', '.btn-file :file', function() {
               var input = $(this),
        label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
    input.trigger('fileselect', [label]);
    });

    $('.btn-file :file').on('fileselect', function(event, label) {

        var input = $(this).parents('.input-group').find(':text'),
            log = label;

        if( input.length ) {
            input.val(log);
        } else {
            if( log ) alert(log);
        }

    });
    function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#img-upload').attr('src', e.target.result);
            }

            reader.readAsDataURL(input.files[0]);
        }
    }

    $("#imgInp").change(function(){
        readURL(this);
    });     
});

提交表单时,我希望它显示已使用 JS 上传的图像并将其“保存”到我的数据库中。

【问题讨论】:

  • “提交表单时,我希望它显示已使用 JS 上传的图像” 在问题代码中阻止&lt;form&gt; 提交的默认操作在哪里?

标签: javascript html mongodb image-uploading jquery-file-upload


【解决方案1】:

“将图像发布到 MongoDB”是什么意思?您不应该将图像保存在数据库中。

您想要做的是,当您上传图片时,将其存储在服务器中可公开访问的位置。您保存在数据库中的不是图像本身,而是图像在服务器上的位置。

图片存储在服务器中: /home/public/image.jpg

存储在 Mongo DB 中的图像路径: { path: '/home/public/image.jpg' }

当您返回到您的 html 页面时,您只需在 Mongo DB 中查询图像的路径,并将该值用作图像标签中的源。

`<img src="${path}" />`

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-22
    • 2011-10-20
    • 2014-11-29
    • 1970-01-01
    • 2019-04-08
    • 2018-10-10
    • 2019-06-13
    • 2015-05-17
    相关资源
    最近更新 更多