前记
第一次接触上传及下载文件,做个总结。
从浏览器上传本地文件
前端
- 本处直接将input上传放在了button内实现。
- 主要利用了input的type=“file” 实现上传框。
- 其中accept可以限制弹出框可选择的文件类型。可限制多种:
:accept="['doc', 'docx']"
- 示例代码
<b-button
class="btn btn-info"
onclick="upload.click()"
>
<input
type="file"
name="upload"
id="upload"
ref="file"
style="display: none;"
@change="onFileSelected"
accept=".png"
/>
</b-button>
methods: {
onFileSelected() {
this.file = this.$refs.file.files[0]
const formData = new FormData()
formData.append('file', this.file)
},
}
注:此处打印formData 显示为空,但实际可以传输,可以打印this.file查看。
- 也可使用以下代码(即b-form-file官方文件选择):
<template>
<div>
<b-form-file v-model="file" @change="onFileSelected"></b-form-file>
<b-button @click="uploadFile">上传</b-button>
</div>
</template>
<script>
import axios from 'axios'
export default {
data() {
return {
file: null
}
},
methods: {
onFileSelected(event) {
this.file = event.target.files[0]
},
uploadFile() {
if (!this.file) {
return
}
let formData = new FormData()
formData.append('file', this.file)
axios.post('/api/upload', formData).then(response => {
console.log(response.data)
})
}
}
}
</script>
接口
- 常用有axios和http
- http: 使用http传输时,加上了Content-Type,但是一直有问题。后来发现代码中给http包装了下,强转了Content-Type的问题,实际直接使用xhr.send(data)即可
http.post('/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
后端
def upload(request):
# 检查是否有文件被上传
if 'file' not in request.files:
return response.json({'error': 'No file uploaded'}, status=400)
# 获取上传的文件对象
file = request.files['file'][0]
# 检查文件类型是否合法,这里以图片为例
if not file.type.startswith('image/'):
return response.json({'error': 'Invalid file type'}, status=400)
# 定义存储目录和文件名
upload_dir = '/path/to/upload/dir'
filename = file.name
# 创建存储目录(如果不存在)
if not os.path.exists(upload_dir):
os.makedirs(upload_dir)
# 保存文件到指定路径
with open(os.path.join(upload_dir, filename), 'wb') as f:
f.write(file.body)
引用
vue文件上传功能bootstrap框架
XMLHttpRequest
文件选择(Form File Input)
Vue使用formData类型上传文件