input type为file时点击上传图片,直接传给后端

此处需引入jquery

写一个input框type为file一个为hidden

<input type="file" value="点击上传" id="ctn-input-file" />
<input type="hidden" name="" id="zhaopian">

在线jquery引用

<script src="https://cdn.wmxxxx.com/js/jquery.js"></script>

这里利用jquery的change事件去监听input值的变化,拿到后端给的图片地址,再赋值给input hidden,然后提交的时候,我们只需要传递图片地址给后端就可以了

$("#ctn-input-file").on("change", function(){
    var formData = new FormData();
    formData.append('file', $('#ctn-input-file')[0].files[0]);
    $.ajax({
        url: "后端上传图片地址",
        type: 'POST',
        cache: false,
        data: formData,
        processData: false,
        contentType: false,
        dataType:"json",
        beforeSend: function(){
            uploading = true;
        },
        success : function(data) {
            console.log(data);
            $('#zhaopian').val(data.res);
        }
    });
});
Last modification:July 3rd, 2019 at 10:40 am
If you think my article is useful to you, please feel free to appreciate

Leave a Comment

简爱博客