vue axiosはbase 64ファイルデータをアップロードし、バックグラウンドでデータを取得できません.
24796 ワード
1.htmlラベル
acceptは、画像ファイルを受け入れるために「image/png,image/gif,image/jpeg」に設定されています.
2.完全なコード
axiosのpostリクエストはonloadに置く必要があります.そうしないと、バックグラウンドではbase 64変換後のデータは受け入れられません.
acceptは、画像ファイルを受け入れるために「image/png,image/gif,image/jpeg」に設定されています.
<input class="upload-file" @change="handleUpload($event)" type="file" id="imgUploader" accept="image/png,image/gif,image/jpeg">
2.完全なコード
axiosのpostリクエストはonloadに置く必要があります.そうしないと、バックグラウンドではbase 64変換後のデータは受け入れられません.
<template>
<div class="upload-form">
<div class="upload-block">
<label class="upload-label">
<i class="icon icon-plus">i>
<img class="upload-img" v-if="upload.src" :src="upload.src" alt=" ">
<input class="upload-file" @change="handleUpload($event)" type="file" id="imgUploader" accept="image/png,image/gif,image/jpeg">
label>
div>
div>
template>
<script type="text/ecmascript-6">
import Toast from 'mint-ui'
import { SUCCESS } from '@/utils/responseStatus'
import Axios from 'axios'
import qs from 'qs'
export default {
data () {
return {
upload: {
src: '',
annexId: ''
},
annex: {
FileName: '',
Extension: '',
AnnexId: '',
Base64Str: '',
Width: 0,
Height: 0
}
}
},
methods: {
handleUpload (e) {
let that = this
// ,
if (!e.target.files[0]) {
return
}
// annex
let file = e.target.files[0]
// 、
let lastIndex = file.name.lastIndexOf('.')
if (lastIndex !== -1) {
that.annex.Extension = file.name.substring(lastIndex + 1)
that.annex.FileName = file.name.substring(0, lastIndex)
}
// base64
// FileReader
let reader = new FileReader()
reader.readAsDataURL(e.target.files[0])
reader.onload = () => {
that.upload.src = reader.result
let idx = reader.result.indexOf(',')
console.log(reader.result)
if (idx !== -1) {
that.annex.Base64Str = reader.result.substring(reader.result.indexOf(',') + 1)
}
let img = new Image()
img.src = reader.result
img.onload = () => {
// , base64、width、height
that.annex.Width = img.width
that.annex.Height = img.height
// qs annex URI encode
let params = qs.stringify({ 'annex': that.annex })
console.log(params)
Axios.post('/AnnexInfo/UploadAnnex', params, {
//
headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' }
}).then(({ data }) => {
console.log(data)
if (data.Code === SUCCESS) {
this.upload.annexId = data.Data
return
}
Toast({
message: data.Message,
iconClass: 'icon icon-warning'
})
}).catch(err => {
Toast({
message: ' , :' + err,
iconClass: 'icon icon-warning'
})
})
}
}
}
}
}
script>
<style lang="stylus" rel="stylesheet/stylus">
.upload-form {
.upload-block {
padding 5px 0
display: flex;
.upload-label {
position: relative;
margin: 0 auto;
width: 100px;
height: 100px;
background-color: #f2f2f2;
border-radius: 8px;
border: solid 1px #cccccc;
color: #CCC;
.icon-plus {
font-size: 39px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
.upload-img {
width: 100%;
height: 100%;
}
.upload-file {
display: none;
}
}
}
}
style>