天天看点

vue实现超级简单的文件上传

前两天刚写完文件上传,在这里记录一下。如果不需要算签名和token认证的话可以把那两行去掉

vue实现超级简单的文件上传
vue实现超级简单的文件上传

html:

<div id="app">
<!--<form enctype="multipart/form-data" action="/auth/fileUploadLocal" method="post">-->
    照片:<input type="file" name="uploadFile"><br/>
    <!--<input type="submit" value="上传">-->
    <button class="login" style="width: 50px;height: 30px;" @click="fileUpload()">上传</button>
<!--</form>-->
    <br/>
    <img :src="file.url" style="width: 410px;height: 600px">
</div>
           

js:

new Vue({
    el: "#app",
    methods: {
        fileUpload: function () {
            console.info("sbkjauth:" + localStorage.getItem("sbkjauth"));
            var _this = this;
            var formData = new FormData();
            formData.append("uploadFile", $("input[name='uploadFile']")[0].files[0]);
            axios({
                method: "post",
                url: "/auth/fileUploadLocal" + getSign(),  // 算签名,不需要可以去掉
                data: formData,
                headers: {
                    'Content-Type': 'multipart/form-data',  // 文件上传
                    // 'Content-Type': 'application/x-www-form-urlencoded',  // 表单
                    // 'Content-Type': 'application/json;charset=UTF-8'  // json
                    "sbkjauth": localStorage.getItem("sbkjauth")  // token ,不需要可以去掉
                },
            }).then(function (response) {
                console.log(response);
                alert(response.data.message);
            }).catch(function (reason) {

            })
        },

    }
});
           

如果发现什么问题请留言,毕竟代码都是人写的难免会出错。