index.vue 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <template>
  2. <div>
  3. <el-upload action=""
  4. :multiple="false"
  5. :show-file-list="false"
  6. accept="image/jpeg,image/png"
  7. class="image-uploader"
  8. :on-exceed="handleExceed"
  9. :on-change="onFrontImgChange"
  10. :before-upload="beforeUpload">
  11. <el-button type="primary" style="width: 200px;" class="mt20">
  12. {{placeholder}}
  13. </el-button>
  14. </el-upload>
  15. </div>
  16. </template>
  17. <script>
  18. import SparkMD5 from 'spark-md5'
  19. import { uploadImg } from "@/components/httpServer/httpServer.js";
  20. import { compressImg } from "../util.js";
  21. export default {
  22. name: 'Upload',
  23. components: {},
  24. props: {
  25. placeholder:{
  26. type: String,
  27. default: "点击上传基准照片",
  28. },
  29. },
  30. data() {
  31. return {
  32. fileMd5:'',
  33. onupload: false,
  34. }
  35. },
  36. methods: {
  37. beforeUpload(file) {
  38. // 限制上传类型
  39. let fileExtensions = ".jpg"
  40. //限制的上限为20M
  41. const max20M = file.size / 1024 / 1024/20;
  42. if (!fileExtensions) {
  43. this.$message.error('上传文件类型只能是 .doc, .docx, .pdf 格式!');
  44. }
  45. if (max20M >1) {
  46. this.$message.error('上传文件大小不能超过 20MB!');
  47. }
  48. return fileExtensions && max20M;
  49. },
  50. handleExceed( event ){
  51. console.log('handleExceed', event)
  52. },
  53. onFrontImgChange:function(file, fileList){
  54. const _this = this //this指向问题
  55. var fileReader = new FileReader();
  56. var dataFile = file.raw;
  57. //console.log(file)
  58. let blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice
  59. var spark = new SparkMD5();
  60. fileReader.readAsBinaryString(dataFile)
  61. //异步执行函数
  62. fileReader.onload = function(e){
  63. spark.appendBinary(e.target.result);
  64. var md5 = spark.end()
  65. _this.fileMd5 = md5;
  66. if( !_this.onupload){
  67. console.log('start', _this.fileMd5)
  68. _this.onupload = true
  69. _this.handleUpload( md5, file.raw )
  70. }else{
  71. console.log("skip", _this.fileMd5 )
  72. }
  73. }
  74. },
  75. handleUpload( rand, file ) {
  76. let that = this
  77. // 100k
  78. compressImg( file, 100 ).then( nfile=>{
  79. console.log( "nfile", nfile)
  80. const formData = new FormData()
  81. formData.append('avatar', nfile )
  82. uploadImg( that.fileMd5, formData ).then( res=>{
  83. that.onupload = false
  84. if( res.code== 200){
  85. that.$emit('onFinish', res.data.url)
  86. }
  87. })
  88. } )
  89. }
  90. }
  91. }
  92. </script>