如何實現最基本的文件(附件)上傳下載?
存儲格式
數據庫建立Blob/Clob/BYTEA格式的字段用于存儲文件的文件流
一、上傳
前端
使用基本的 file type類型input。
使用過程中發現該類型默認顯示中文,可將其隱藏,添加新的控件來觸發此input控件的輸入。
input.form-control( type='file' @change="handleGetFile" style="display:none" ref="fileInput" )
.input-group
input.form-control.form-control-sm( type="text" v-model.trim="fileToUpload.file_name" readonly )
.input-group-append
.input-group-btn.btn.btn-sm.btn-info( @click="$refs.fileInput.click()" ) Browse
使用FormData包裝file數據,并post到后臺服務
handleGetFile(data) {
let formData = new FormData()
formData.append("context_id", this.contextId)
formData.append("file_data", data.target.files[0])
formData.append("file_name", data.target.files[0].name)
formData.append("file_size", data.target.files[0].size)
this.$axios.post('url', formData)
}
后臺(python)
在request中取files的數據
# file object hat is being uploaded.
file_data = request.files['file_data']
# read the stream of the file
bin_data = file_data.read()
將bin_data存儲數據庫Blob/BYTEA字段
二、下載
后臺
返回blob/bytea字段file stream數據
前端
前端發送get請求,需要將responseType設為blob,默認為json。
this.$axios.get(`url`, {responseType: 'blob'})
收到response的file stream數據后,創建Blob對象并下載該對象
downloadAttachment(attachment, response.data) {
const blob = new Blob([response.data], {type: attachment.file_type, name: attachment.file_name})
if ('download' in document.createElement('a')) {
const link = document.createElement('a')
link.fileName = attachment.file_name
link.style.display = 'none'
link.href = URL.createObjectURL(blob)
link.setAttribute('download', attachment.file_name)
document.body.appendChild(link)
link.click()
URL.revokeObjectURL(link.href)
document.body.removeChild(link)
}
else {
navigator.msSaveBlob(blob, attachment.file_name)
}
}