upload 上传图片(简易)
XML/HTML Code复制内容到剪贴板
- <div class="necessary_list">
- <div class="necessary_header clear">
- <div class="fl">封面</div>
- <div class="fr btn_group">
- <button class="uploadBtn">
- 选择
- <input type="file" class="uploadImageInput" @change="uploadImage($event)">
- </button>
- <button>拍照</button>
- </div>
- </div>
- <div class="necessary_text">
- <input type="file" id="imageUpload" accept="image/*" style="display: none;">
- <img :src="coverImage" alt="上传图测试" id="coverImg">
- </div>
- </div>
上传表单绑定uploadImage的change事件,传this当前对象,在coverImage中指定默认图片,上传成功后更改默认图片的url,
JavaScript Code复制内容到剪贴板
- uploadImage(event) {
- var files = event.target.files || event.dataTransfer.files;
- if(!files.length) return;
- // console.log(files);
- // return false;
- this.createImage(files);
- },
- createImage(file) {
- if(typeof FileReader === "undefined") {
- alert("您的浏览器不支持图片上传,请升级您的浏览器");
- return false;
- }
- let image = new Image();
- let leng = file.length;
- let reader = new FileReader();
- let userId = localStorage.getItem("userId") ? userId = localStorage.getItem("userId") : 1;
- let publishId = this.$route.params.id;
- let that = this;
- reader.readAsDataURL(file[0]);
- reader.onload = function(e) {
- let params = {};
- params.images = e.target.result;
- params.userId = userId;
- params.publish_id = publishId;
- that.request.post(that.$store.state.cms.api.uploadCoverImage, params).then(response => {
- let res = response.data;
- if(res.code == 0) {
- // 更改封面图片路径
- that.coverImage = res.data;
- } else {
- Toast(res.msg);
- }
- }, response => {
- console.log(response);
- // error callback
- })
- };
- },
type=file的上传表单的onchange事件,在执行过一次之后,再次点击,不再触发的解决办法,重新克隆一个对象并替换上去:
JQ的写法:
XML/HTML Code复制内容到剪贴板
- <script>
- $(function(){
- form.reset(); //清除浏览器记录的上次记录
- var file;
- $(form).on("change","#file",function(e){
- //输出选中结果
- console.log(this.value);
- //每次选中都保存旧元素,并使用新的控件替换
- $(this).clone().replaceAll(file=this);
- }).submit(function(){
- //提交时把之前保存的旧元素替换回去
- $("#file").replaceWith(file);
- });
- });
- </script>
- <form id="form">
- <input type="file" name="file" id="file"><br/>
- <input type="submit" />
- </form>
下一篇 Javascript数组操作