【问题标题】:send Uploaded image data to node server将上传的图像数据发送到节点服务器
【发布时间】:2018-05-04 08:56:15
【问题描述】:

我正在使用 node.js 并在单击加号字形图标后测试如何上传图像(下图)。如何将选择的图像发送到服务器?我之前上传了图片,但那是在处理发布请求的表单中。 Afterwrds 我会在服务器端使用 Multer 来处理它。在这里,我不知道选择图像作为个人资料图片后该怎么办。我在考虑 imageIsLoaded() 函数中的 $.post ,但我不知道要添加什么作为数据。

我可以在下面给出的示例中更改 src 属性,但我想将所选图像永久保存在服务器上。

This is how the website looks

客户端JS文件

$("#upload").on('click',function() {
    $("input[type='file']").click();
});

$(":file").change(function () {
    if (this.files && this.files[0]) {
        var reader = new FileReader();
        reader.onload = imageIsLoaded;
        reader.readAsDataURL(this.files[0]);
    }
});

function imageIsLoaded (e) {
    console.log('heloooooo')
    $('.profileImg').attr('src', e.target.result);
}

EJS

<div class="profileImgSection">
        <% if (user.profilePicture.uploaded === false) { %>
        <span id="upload" class="glyphicon glyphicon-plus-sign"></span>
        <input type='file'  />

        <img class="profileImg"
             src="<%="images/pexels-photo-370799.jpeg"%>"
             alt="fail">
        <% } else { %>
        <img class="profileImg"
             src="<%=user.profilePicture.link%>"
             alt="fail">
        <% } %>
    </div>

CSS 文件

input[type='file'] {
    display: none;
}

【问题讨论】:

    标签: javascript jquery node.js image-uploading multer


    【解决方案1】:

    当文件选择器更改时,您可以预览图像并通过 ajax 上传, HTML

    <form id="form" enctype="multipart/form-data">
      <input type='file' onchange="readURL(this);" />
    </form>
    <img id="preview" src="#" alt="your image" />
    

    JS

     function readURL(input) {
                if (input.files && input.files[0]) {
                    var reader = new FileReader();
    
                    reader.onload = function (e) {
                        $('#preview')
                            .attr('src', e.target.result)
                            .width(150)
                            .height(200);
                    };
    
                    reader.readAsDataURL(input.files[0]);
    
                    //ajax post here
                     $.ajax({
                         url: '',
                        method: 'POST',
                        data: new FormData($('#form')[0])
                      }).done(function (data) {
    
                      }).fail(function(jqXHR, textStatus, errorThrown){
    
                      });
                }
            }
    

    【讨论】:

      猜你喜欢
      • 2012-12-11
      • 1970-01-01
      • 1970-01-01
      • 2016-08-19
      • 2015-04-01
      • 1970-01-01
      • 2021-08-04
      • 2021-07-07
      • 1970-01-01
      相关资源
      最近更新 更多