vue element ui上传图片并预览

2021年3月27日 18:44 by wst

vue

起因:

前端在上传图片的时候,希望能显示下预览。

过程:

经过在网上各种搜索,加上自己的总结,终于解决。

结果

主要逻辑是:通过文件阅读器把上传的图片文件转成二进制形式放到url里

形成如下的代码:

<template>
  <div class="main_item">
    <div class="itemLeft">
      <span class="must">商品缩略图</span>
    </div>
    <div class="itemRight">
      <!-- itemRight2 -->
      <el-upload
        action="http://localhost:8080"
        v-model="imageUrl.file"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :on-error="uploadError"
        :before-upload="beforeAvatarUpload"
        accept="image/png, image/jpg, image/jpeg"
        class="avatar-uploader"
      >
        <img v-if="imageUrl.url" :src="imageUrl.url" class="avatar" />
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      imageUrl: {
        url: null,
        file: null,
      },
    };
  },
  methods: {
    // 图片上传成功提示
    handleAvatarSuccess(res, file, fileList) {
      this.$message({
        center: true,
        message: "图片上传成功",
        type: "success",
      });
    },

    uploadError() {
      // ?不需要,上传失败操作
    },
    //上传前回调
    beforeAvatarUpload(file) {
      // ++
      console.log(file);
      this.imageUrl.file = file;
      this.imagePreview(this.imageUrl.file, 1);
      return false;
    },
    //**重点**,上传的文件转化为base64格式,用于展示
    imagePreview(file, v) {
      var self = this;
      //定义一个文件阅读器
      var reader = new FileReader();
      //文件装载后将其显示在图片预览里
      reader.onload = function (e) {
        //将bade64位图片保存至数组里供上面图片显示
        if (v == 1) {
          self.imageUrl.url = e.target.result;
        } 
      };
      reader.readAsDataURL(file);
    },
  },
};
</script>


<style scoped>
.main_item {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  width: 100%;
  height: 100%;
  background: #f3f3f3;
  box-sizing: border-box;
}
.itemLeft {
  line-height: 1;
  font-size: 60px;
  font-weight: bolder;
  color: #3a17d6;
  height: auto;
  width: 50%;
  margin-bottom: 30px;
}
.itemRight {
  height: auto;
  width: 50%;
}
.avatar {
  height: auto;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-content: center;
  justify-content: center;
}
.avatar-uploader-icon {
    font-size: 30px;
}

</style>

优化

现在大多是前后端分离的,在调试时,需要设置代理。但是el-upload组件是直接上传的,这里要重写http-request属性。

思路是:

1. 先写一个上传文件的公共服务;

2. 在当前页定义一个函数:组装formData数据,然后传递给那个公共服务;

代码如下:

公共服务:这里的request是经过axios重写过的,想知道怎么重写请百度。

export function upload_image(query){
    return request({
        url: '/boss/admin/upload/image',
        method: 'post',
        data: query,
        headers: {'Content-Type': 'multipart/form-data'}
    })
}

 上传文件函数:组装formData数据并上传

import { upload_image } from "../../api/index";

upLoadImage(param){
      let formData = new FormData();
      formData.append("file", param.file);
      formData.append("files", param.files);
      upload_image(formData).then(res=>{
        this.form.file = res.data.file
      })
}

组件参数:覆盖http-request属性

<el-upload 
<el-upload 
:action="uploadActionUrl" 
:before-upload="beforeAvatarUpload"
:show-file-list="true" 
:file-list="[form.file]"
:http-request="upLoadImage"
accept="image/png, image/jpg, image/jpeg"
list-type="picture"
>
  <el-button size="small" type="primary">点击上传</el-button>
  <div slot="tip" class="el-upload__tip">请上传图片格式文件</div>
</el-upload>

如有问题,请留言!


Comments(130) Add Your Comment

wst
<el-upload :action="uploadActionUrl" v-model="form.file" :show-file-list="false" :on-success="handleAvatarSuccess" accept="image/png, image/jpg, image/jpeg" :before-upload="beforeAvatarUpload" :on-change="onUploadChange" :auto-upload="true" :http-request="uploadSectionFile" > <el-button size="small" type="primary">点击上传</el-button> </el-upload> uploadSectionFile(params){ var formData = new FormData(); formData.append("file", params.file); upload_image(formData).then(res=>{ console.log("resup:", res) this.$message({ center: true, message: "图片上传成功", type: "success", }); return true }) return false }
Charlesnag
“I haven’t seen you in these parts,” the barkeep said, sidling over to where I sat. “Personage’s Bao.” He stated it exuberantly, as if solemn word of honour of his exploits were shared aside settlers around multitudinous a verve in Aeternum. He waved to a wooden keg beside us, and I returned his gesture with a nod. He filled a glass and slid it to me across the stained red wood of the court first continuing. “As a betting man, I’d be ready to wager a above-board portion of coin you’re in Ebonscale Reach for the purpose more than the drink and sights,” he said, eyes glancing from the sword sheathed on my in to the salaam slung across my back. https://www.google.com.ec/url?q=https://renewworld.ru/new-world-kak-popast-na-alfa-i-beta-testy/
Kevingaw
https://sonnenreiter.de/wp-includes/pgs/?welches_online_casino_ist_zu_empfehlen_3.html https://www.google.lv/url?sa=f&rct=j&url=http://cloudbetwelcomebonus.com/fr/ https://www.google.cd/url?q=https://1xbitapk.com/pl/ https://images.google.vg/url?q=http://cloudbetwelcomebonus.com/ https://www.hille-eventservice.de/news/wettannahmestellen_in_polen.html
Kevingaw
http://www.google.com.mm/url?sa=t&rct=j&q=the+beginning+of++the+baptist+pdf&source=web&cd=28&ved=0CGAQFjAHOBQ&url=https://1xbitapk.com/es/ https://maps.google.at/url?q=https://druckerei-festge.de/wp-content/pages/welches_casino_zahlt_am_schnellsten_aus___ein_casino_mit_einer_guten_auszahlungsrate.html https://images.google.com.vn/url?q=https://druckerei-festge.de/wp-content/pages/welches_casino_zahlt_am_schnellsten_aus___ein_casino_mit_einer_guten_auszahlungsrate.html https://sen7.com/typo3/inc/?welches_casino_zahlt_am_schnellsten_aus____bewertung_von_online_casinos_top_10.html https://www.google.ad/url?sa=t&source=web&cd=1&sqi=2&ved=0cbwqfjaa&url=https://1xbitapk.com/hi/
Dlango
atorvastatin 80mg cheap <a href="https://lipiws.top/">lipitor 10mg over the counter</a> lipitor drug
Gcyjyk
purchase ciprofloxacin without prescription - <a href="https://cipropro.top/bactrimos/">bactrim 960mg price</a> order augmentin 375mg pill
Bfykge
order baycip generic - <a href="https://metroagyl.top/">order cipro without prescription</a> how to buy clavulanate
Qujuqa
buy ciprofloxacin 500mg without prescription - <a href="https://septrim.top/tinidazole/">order tinidazole pill</a> order generic erythromycin
Mnylah
how to get metronidazole without a prescription - <a href="https://metroagyl.top/cefaclor/">order cefaclor 250mg online cheap</a> azithromycin 250mg us
Vmqjnn
ivermectin 12 mg - <a href="https://keflexin.top/cefixime/">buy cefixime 100mg online</a> sumycin generic
Ntbyhb
buy valacyclovir 500mg for sale - <a href="https://gnantiviralp.com/nemasole/">purchase nemasole generic</a> acyclovir online order
Hqcqvz
how to buy acillin <a href="https://ampiacil.top/doxycyclineantb/">vibra-tabs pills</a> buy generic amoxil over the counter
Ybodzu
order flagyl 200mg - <a href="https://metroagyl.top/">flagyl 200mg usa</a> buy zithromax 250mg online
Tzuohk
lasix 100mg cheap - <a href="https://antipathogenc.com/prograf/">tacrolimus tablet</a> order captopril 25 mg sale
Nttabk
glucophage 1000mg uk - <a href="https://gnantiacidity.com/septra/">order bactrim 960mg pills</a> lincomycin 500 mg usa
Mxjdsj
order retrovir 300 mg generic - <a href="https://canadiangnp.com/epivir/">cheap epivir 100mg</a> zyloprim 300mg drug
Icxizk
buy generic clozaril 50mg - <a href="https://genonlinep.com/pepcid/">order famotidine 40mg online cheap</a> pepcid usa
Cbxiib
buy quetiapine for sale - <a href="https://gnkantdepres.com/effexor/">venlafaxine 75mg price</a> buy eskalith tablets
Ybkbsi
anafranil for sale online - <a href="https://antdeponline.com/remeron/">buy mirtazapine 30mg sale</a> where can i buy sinequan
Tfgzns
atarax 25mg brand - <a href="https://antdepls.com/pamelor/">cost nortriptyline</a> generic endep 25mg
Qnpkin
brand augmentin - <a href="https://atbioinfo.com/ampicillin/">ampicillin ca</a> buy cipro 500mg pill
Fiszll
buy amoxicillin paypal - <a href="https://atbioxotc.com/cefadroxil/">cefadroxil tablet</a> buy cipro online
Dqgocd
buy zithromax 250mg for sale - <a href="https://gncatbp.com/aciprofloxacin/">where can i buy ciplox</a> buy ciplox 500mg online
Gyggwf
buy clindamycin without a prescription - <a href="https://cadbiot.com/doxycycline/">purchase vibra-tabs online cheap</a> chloromycetin order
Yobbuv
ivermectin 3 mg oral - <a href="https://antibpl.com/tylquin/">levaquin 500mg brand</a> order cefaclor 500mg pills
Lrfpdz
buy cheap generic ventolin - <a href="https://antxallergic.com/cvallegra/">cost fexofenadine 120mg</a> how to buy theophylline
Xtnybl
medrol 16mg without a doctor prescription - <a href="https://ntallegpl.com/getazelastine/">purchase azelastine sprayers</a> buy generic azelastine
Cvmzey
order desloratadine 5mg online - <a href="https://rxtallerg.com/beclomethasone/">where to buy beclomethasone without a prescription</a> purchase albuterol inhaler
Xxmemp
micronase 5mg cheap - <a href="https://prodeprpl.com/">buy micronase pills</a> forxiga cost
Zlfjvo
buy glucophage without prescription - <a href="https://arxdepress.com/acarbose50/">purchase precose generic</a> order acarbose 50mg sale
Qjfnra
buy generic prandin for sale - <a href="https://depressinfo.com/jardiance25/">generic jardiance</a> order jardiance 25mg for sale
Exqagw
rybelsus price - <a href="https://infodeppl.com/">buy semaglutide online cheap</a> desmopressin online
Xawhmp
oral lamisil - <a href="https://treatfungusx.com/">generic lamisil 250mg</a> griseofulvin over the counter
Zoxdfm
famciclovir uk - <a href="https://amvinherpes.com/">famvir 500mg usa</a> buy valcivir 1000mg sale
Acqibn
oral digoxin - <a href="https://blpressureok.com/avalidemed/">avapro 300mg brand</a> order generic furosemide 40mg
Fxztzo
metoprolol tablet - <a href="https://bloodpresspl.com/olmesartan/">order benicar 20mg for sale</a> adalat cheap
Yxiqtw
generic hydrochlorothiazide 25mg - <a href="https://norvapril.com/bisoprolol/">bisoprolol 10mg uk</a> order zebeta 5mg generic
Knzyed
nitroglycerin cost - <a href="https://nitroproxl.com/catapres/">clonidine without prescription</a> order valsartan 160mg for sale
Goisrh
zocor motor - <a href="https://canescholest.com/atorvastatin/">lipitor marsh</a> atorvastatin fault
Wnusls
crestor slop - <a href="https://antcholesterol.com/">crestor pills weapon</a> caduet uncomfortable
Vwahtc
viagra professional incident - <a href="https://edsildps.com/">viagra professional online haul</a> levitra oral jelly remembrance
Nwhnoc
dapoxetine courage - <a href="https://promedprili.com/suhagra/">suhagra shower</a> cialis with dapoxetine impress
Msgpcj
cenforce online below - <a href="https://xcenforcem.com/silagrasildenafil/"></a> brand viagra pills guess
Zrbjfd
brand cialis grass - <a href="https://probrandtad.com/apcalissx/">apcalis swim</a> penisole shadowy
Ftmmut
brand cialis doom - <a href="https://probrandtad.com/alprostadilonline/">alprostadil bitter</a> penisole criminal
Rebqwp
cialis soft tabs online interval - <a href="https://supervalip.com/">cialis soft tabs pills again</a> viagra oral jelly dawn
Ylsvpb
cialis soft tabs online face - <a href="https://supervalip.com/viagrasuperactive/">viagra super active pills awake</a> viagra oral jelly online league
Akqjmp
dapoxetine wrought - <a href="https://promedprili.com/">priligy cream</a> cialis with dapoxetine tire
Smsmmn
cenforce online scar - <a href="https://xcenforcem.com/silagrasildenafil/"></a> brand viagra pills accurse
Ularrv
asthma treatment stretch - <a href="https://bsasthmaps.com/">asthma treatment night</a> asthma treatment dale
Iadvtv
acne medication bell - <a href="https://placnemedx.com/">acne treatment breast</a> acne treatment heaven
Wstfun
prostatitis treatment equal - <a href="https://xprosttreat.com/">prostatitis pills real</a> pills for treat prostatitis threat
Uxxqwl
uti medication waiter - <a href="https://amenahealthp.com/">uti medication glint</a> uti medication court
Ctgyls
loratadine medication peeve - <a href="https://clatadine.top/">claritin pills whoever</a> loratadine medication afford
Afxgsm
valacyclovir online hasten - <a href="https://gnantiviralp.com/">valacyclovir online ride</a> valtrex pills pirate
Heizym
dapoxetine terrace - <a href="https://prilixgn.top/">dapoxetine fleet</a> priligy address
Mvgcyl
loratadine medication weight - <a href="https://clatadine.top/">claritin pills bird</a> claritin pills realize
Dziyex
ascorbic acid clothe - <a href="https://ascxacid.com/">ascorbic acid rail</a> ascorbic acid proof
Xhwpza
promethazine depart - <a href="https://prohnrg.com/">promethazine report</a> promethazine horror
Nnzitv
biaxin nobody - <a href="https://gastropls.com/mesalaminepl/">asacol clever</a> cytotec pills saint
Bftfnw
fludrocortisone pills steel - <a href="https://gastroplusp.com/propantoprazole/">protonix victim</a> prevacid pills entity
Chmcln
generic aciphex 10mg - <a href="https://gastrointesl.com/">order rabeprazole for sale</a> domperidone 10mg brand
Qnllaq
buy dulcolax without prescription - <a href="https://gastroinfop.com/oxybutynin/">oral oxytrol</a> liv52 online
Ctjftg
how to get hydroquinone without a prescription - <a href="https://cerazestrel.com/">how to get cerazette without a prescription</a> cheap dydrogesterone 10mg
Fggdux
bactrim 960mg oral - <a href="https://tobmycin.com/">tobramycin tablet</a> buy tobrex generic
Wcbdrr
griseofulvin 250mg over the counter - <a href="https://gemfilopi.com/">buy cheap generic gemfibrozil</a> order gemfibrozil generic
Ndqgiy
order dapagliflozin 10 mg generic - <a href="https://forpaglif.com/">forxiga 10mg sale</a> order precose
Ogzowj
dimenhydrinate 50mg without prescription - <a href="https://prasilx.com/">buy prasugrel for sale</a> actonel uk
Xqmzqo
order vasotec 5mg generic - <a href="https://vasolapril.com/">cost vasotec 5mg</a> xalatan cheap
Ziakwd
order etodolac 600mg for sale - <a href="https://etodograph.com/">monograph online order</a> buy pletal 100 mg for sale
Xmpduq
order piroxicam 20mg without prescription - <a href="https://feldexicam.com/">feldene price</a> order exelon 6mg for sale
Noqcot
buy nootropil 800 mg sale - <a href="https://nootquin.com/secnidazole/">order secnidazole 10mg generic</a> buy generic sinemet online
Plaike
purchase hydroxyurea for sale - <a href="https://hydroydrinfo.com/methocarbamol/">buy robaxin cheap</a> robaxin cheap
Xmvekg
order depakote 250mg online - <a href="https://adepamox.com/">buy depakote 250mg online</a> topiramate 200mg canada
Akuchk
disopyramide phosphate over the counter - <a href="https://anorpica.com/">cheap norpace pills</a> thorazine 50 mg pill
Ahccen
order aldactone 100mg sale - <a href="https://aldantinep.com/dipyridamole/">persantine generic</a> revia cheap
Ehfikc
cytoxan canada - <a href="https://cycloxalp.com/atomoxetine/">buy strattera online</a> purchase trimetazidine for sale
Oykhvs
order flexeril 15mg generic - <a href="https://abflequine.com/donepezil/">purchase aricept sale</a> enalapril 10mg for sale
Uxvdav
ondansetron for sale online - <a href="https://azofarininfo.com/tolterodine/">where can i buy tolterodine</a> ropinirole 2mg pill
Jgsdka
ascorbic acid ca - <a href="https://mdacidinfo.com/isosorbidedinitrate/">isosorbide dinitrate price</a> buy generic compro
Vbdqel
durex gel purchase online - <a href="https://xalaplinfo.com/latanoprosteyedrops/">zovirax buy online</a> zovirax medication
Nkturm
cheap minoxidil generic - <a href="https://hairlossmedinfo.com/finasteridehl/">buy finasteride 5mg online</a> buy proscar 5mg
Hctsqv
buy leflunomide without a prescription - <a href="https://infohealthybones.com/">buy leflunomide medication</a> order cartidin online
Npettm
brand calan 120mg - <a href="https://infoheartdisea.com/valsartan/">order valsartan online</a> buy tenoretic for sale
Njwuju
order atenolol 100mg sale - <a href="https://heartmedinfox.com/">tenormin 50mg canada</a> buy carvedilol pill
Hdorad
cheap atorvastatin for sale - <a href="https://infoxheartmed.com/nebivolol/">buy generic bystolic 20mg</a> nebivolol 5mg usa
Dnjqvq
order gasex generic - <a href="https://herbalinfomez.com/">how to buy gasex</a> cost diabecon
Lyhvqa
purchase lasuna online cheap - <a href="https://infoherbalmz.com/">buy lasuna online cheap</a> cheap himcolin without prescription
Tinlge
order noroxin for sale - <a href="https://gmenshth.com/confido/">order confido generic</a> buy confido for sale
Pqbrec
buy finax online - <a href="https://finmenura.com/alfuzosin/">buy alfuzosin online cheap</a> order alfuzosin 10 mg generic
Chzksv
hytrin where to buy - <a href="https://hymenmax.com/tamsulosin/">flomax 0.2mg oral</a> dapoxetine 30mg drug
Pqoqlj
order speman online - <a href="https://spmensht.com/himplasia/">himplasia price</a> fincar brand
Sxmlth
trileptal pills - <a href="https://trileoxine.com/">order trileptal generic</a> buy levothyroxine paypal
Dkugbn
cyclosporine us - <a href="https://asimusxate.com/">imusporin where to buy</a> colchicine price
Jxzseg
buy duphalac generic - <a href="https://duphalinfo.com/mentat/">buy mentat paypal</a> betahistine price
Xdwxkr
order generic calcort - <a href="https://lazacort.com/">buy deflazacort generic</a> brand alphagan
Eoozwc
buy besifloxacin eye drops - <a href="https://besifxcist.com/sildamax/">purchase sildamax online cheap</a> cheap sildamax online
Uwajhe
buy gabapentin 600mg online - <a href="https://aneutrin.com/sulfasalazine/">buy azulfidine 500mg pills</a> azulfidine pill
Vpskgr
benemid 500mg drug - <a href="https://bendoltol.com/">how to get benemid without a prescription</a> buy carbamazepine 200mg generic
Zwcptx
buy celecoxib 200mg sale - <a href="https://celespas.com/">buy celecoxib 100mg online cheap</a> indocin price
Ermcfw
mebeverine 135 mg tablet - <a href="https://coloxia.com/">buy mebeverine online</a> buy cilostazol 100mg for sale
Jlpwev
buy diclofenac 100mg sale - <a href="https://dicloltarin.com/aspirin/">aspirin tablet</a> aspirin where to buy
Rxgtvu
cheap generic rumalaya - <a href="https://rumaxtol.com/shallaki/">cheap shallaki pills</a> order elavil 10mg for sale
Omouwx
purchase pyridostigmine generic - <a href="https://mestonsx.com/azathioprine/">buy cheap azathioprine</a> azathioprine price
Nghsei
order ozobax sale - <a href="https://baclion.com/">baclofen 10mg ca</a> feldene order online
Vymuok
purchase diclofenac - <a href="https://vovetosa.com/tisosorbide/">purchase isosorbide without prescription</a> purchase nimodipine online cheap
Skiyeu
order cyproheptadine 4 mg online - <a href="https://periheptadn.com/">buy periactin 4 mg generic</a> buy tizanidine
Zkacxe
generic mobic 7.5mg - <a href="https://meloxiptan.com/">oral meloxicam 15mg</a> order toradol online cheap
Yhgysp
order omnicef without prescription - <a href="https://omnixcin.com/aminocycline/"></a> buy clindamycin sale
Ivxprx
generic trihexyphenidyl - <a href="https://voltapll.com/diclofenacgel/">diclofenac gel online order</a> buy emulgel sale
Ioqbkr
where can i buy accutane - <a href="https://aisotane.com/">accutane 20mg us</a> deltasone 20mg usa
Jpsxcu
deltasone 20mg over the counter - <a href="https://apreplson.com/permethrin/">buy elimite paypal</a> buy zovirax no prescription
Jcaoif
acticin over the counter - <a href="https://actizacs.com/">permethrin generic</a> order retin cream
Whfjhk
betnovate 20 gm cheap - <a href="https://betnoson.com/">betnovate canada</a> buy benoquin online
Khjbcw
how to buy flagyl - <a href="https://cenforcevs.com/">cenforce 100mg cost</a> buy cenforce 50mg
Qujzyl
order augmentin 1000mg generic - <a href="https://baugipro.com/">augmentin 375mg usa</a> levothroid oral
Twvuwe
hyzaar without prescription - <a href="https://acephacrsa.com/">buy keflex 250mg pills</a> order keflex 250mg generic
Fuowhv
cleocin drug - <a href="https://indometnp.com/">order indomethacin sale</a> indocin order
Ujhncn
buy eurax cream for sale - <a href="https://aeuracream.com/">buy generic eurax online</a> buy aczone sale
Yprkto
order provigil 200mg - <a href="https://sleepagil.com/melatonin/">melatonin tablet</a> cheap melatonin
Ptmyzt
cheap xeloda - <a href="https://xelocap.com/mefenamicacid/">ponstel online</a> danocrine for sale
Kkdexd
progesterone canada - <a href="https://apromid.com/clomiphene/">clomiphene cheap</a> brand fertomid
Nmapvx
order alendronate 70mg online - <a href="https://pilaxmax.com/">cost fosamax 35mg</a> order medroxyprogesterone 5mg without prescription
Stysnn
order aygestin 5 mg generic - <a href="https://norethgep.com/yasmin/">cheap yasmin without prescription</a> yasmin sale
Qgonvs
estrace 1mg price - <a href="https://festrolp.com/ginette-35/">buy ginette 35 generic</a> buy generic arimidex 1 mg
Vluhox
order cabergoline 0.25mg generic - <a href="https://adostilin.com/cabgolin/">cabgolin oral</a> order alesse online cheap
Hepavo
プレドニン - 5mg - <a href="https://jpaonlinep.com/jamoxicillin/">アモキシシリン通販 安全</a> アジスロマイシンジェネリック 通販
Jtwbux
バイアグラ 海外通販 - <a href="https://jpedpharm.com/">シルデナフィル 値段</a> タダラフィル の購入
Jxfdnj
プレドニン通販 - <a href="https://jpanfarap.com/jpaaccutane/">イソトレチノイン 副作用</a> アキュテイン通販 安全
Xhqjkm
eriacta truck - <a href="https://eriagra.com/">eriacta impatient</a> forzest english