1.项目介绍
这个小demo实现图片列表循环展示,并在点击某一张图片时,重新上传图片覆盖原来的图片。
前端: vue3 + ant design
后端:python flask
2.前端代码
uploadImg.vue
<template>
<div class="pptdetail">
<template v-for="(item, index) in pptlist" :key="item">
<a-form
:model="item"
:scrollToFirstError="true"
class="showform">
<a-input v-model:value= item.id class="unid"/>
<a-input v-model:value= item.time />
<a-input v-model:value= item.imgUrl />
<!-- 重点!-->
<!-- beforupload 有原设参数,为操作的文件file, 此时如何将对应的index传入呢?-->
<a-upload
accept="image/*"
:show-upload-list="false"
:before-upload=" file => {
beforeUploadImg (file, index)
}"
class = "imgup"
>
<img v-if=item.imgUrl :src=item.imgUrl alt="图片加载错误" class="showimg" >
<div v-else>
<loading-outlined v-if="loading"></loading-outlined>
<plus-outlined v-else></plus-outlined>
</div>
</a-upload>
</a-form>
</template>
</div>
</template>
<script>
import { message } from 'ant-design-vue'
import { defineComponent, ref, reactive } from 'vue'
import axios from 'axios'
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons-vue'
setup(){
const pptlist = reactive([
{
id: '1',
imgUrl: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
time: '00:30'
},
{
id: '2',
imgUrl: 'https://gw.alipayobjects.com/zos/antfincdn/LlvErxo8H9/photo-1503185912284-5271ff81b9a8.webp',
time: '01:00'
}])
const beforeUploadImg = (file, index) => {
const isLt2MB = file.size / 1024 / 1024 < 2
if (!isLt2MB) {
message.error('上传的图片大小不能超过2MB!')
return false
}
const fd = new FormData()
fd.append('file', file)
axios({
method: 'post',
url: 'http://127.0.0.1:5000/uploadimg',
data: fd,
headers: { 'Content-Type': 'multipart/form-data' }
}).then(res => {
console.log(res.data)
if (res.data.code === 200) {
pptlist[index].imgUrl = res.data.url
message.success('上传成功!')
} else {
message.error('上传失败!')
}
})
return false
}
return {
pptlist,
beforeUploadImg
}
}
})
</script>
3.后端代码
import os
from flask import Flask,request
from flask_cors import CORS
# 创建Flask实例
app = Flask(__name__,static_folder='uploadimg')
# 全局API配置跨域
cors = CORS(app,origins = '*')
# Flask触发函数的URL
@app.route('/uploadimg', methods = ['POST'])
def uploadImg():
file = request.files.get('file')
if file is None: # 表示没有发送文件
return {
'message': "文件上传失败"
}
file_name = file.filename.replace(" ", "")
print("获取上传文件的名称为[%s]\n" % file_name)
file.save(os.path.dirname(__file__) + '/uploadimg/' + file_name) # 保存文件
file_path = 'http://127.0.0.1:5000/uploadimg/'+ file_name
return {
'code': 200,
'messsge': "文件上传成功",
'fileName': file_name,
'url': file_path,
}
if __name__ == '__main__':
# 默认host为127.0.0.1,port为5000
app.run(host='127.0.0.1', port=5000, debug=True)