File uploading is a common requirement of our daily development. In the previous ERA of IE, cross-domain uploading was very troublesome, and iframe was used as a relay. Now it is much more convenient.

Technical points:

  • Triggers the change event for the file selection controldispatchEvent(new MouseEvent('click')Because we typically hide the native file input, we use a button designed to trigger the file selection action
  • Read the selected filee.target.files
  • usingFileReaderObject reads the image base64 for preview
  • usingFormDataObject to upload

The code is as follows:

<template> <div> <input style="opacity: 0.3;" ref="filElem" type="file" accept="image/*" @change="changeFile($event)"> <br><button type="button" <img height="200" : SRC ="imgsrcLocal"> <br><img height="200" : SRC ="imgsrcServe"> </div> </div> </template> <script> export default { data() { return { imgsrcLocal: '', imgsrcServe: null } }, methods: {{/ / trigger file input changeImg (). This $refs. FilElem. DispatchEvent (new MouseEvent (' click ')}, changeFile(e) { console.log(this.$refs.filElem.value) console.log(e.target.value) let file0 = e.target.files[0] Console. log(file0) // File preview const reader = new FileReader(); reader.readAsDataURL(file0); console.log(reader) reader.onload = (img) => { this.imgsrcLocal = img.target.result; } const formData = new FormData(); formData.append('file', file0) this.$axios({ method: "POST", url: "/v1/uploadFile", //"content-type": "application/json; charset=UTF-8", withCredentials: true, data: formData }).then(res => { console.log(res) this.imgsrcServe = res.data.src }).catch(err => { console.log(err) }) } } } </script>Copy the code