文件上傳下載 Blob格式存儲

如何實現(xiàn)最基本的文件(附件)上傳下載?

存儲格式

數(shù)據(jù)庫建立Blob/Clob/BYTEA格式的字段用于存儲文件的文件流

一、上傳

前端

使用基本的 file type類型input。
使用過程中發(fā)現(xiàn)該類型默認顯示中文,可將其隱藏,添加新的控件來觸發(fā)此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數(shù)據(jù),并post到后臺服務(wù)

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的數(shù)據(jù)

# 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存儲數(shù)據(jù)庫Blob/BYTEA字段

二、下載

后臺

返回blob/bytea字段file stream數(shù)據(jù)

前端

前端發(fā)送get請求,需要將responseType設(shè)為blob,默認為json。

this.$axios.get(`url`, {responseType: 'blob'})

收到response的file stream數(shù)據(jù)后,創(chuàng)建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)
  }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 以ASP.NET Core WebAPI作后端API,用Vue構(gòu)建前端頁面,用Axios從前端訪問后端API ,包...
    jianshu1212閱讀 966評論 0 0
  • 久違的晴天,家長會。 家長大會開好到教室時,離放學(xué)已經(jīng)沒多少時間了。班主任說已經(jīng)安排了三個家長分享經(jīng)驗。 放學(xué)鈴聲...
    飄雪兒5閱讀 7,845評論 16 22
  • 今天感恩節(jié)哎,感謝一直在我身邊的親朋好友。感恩相遇!感恩不離不棄。 中午開了第一次的黨會,身份的轉(zhuǎn)變要...
    余生動聽閱讀 10,894評論 0 11
  • 可愛進取,孤獨成精。努力飛翔,天堂翱翔。戰(zhàn)爭美好,孤獨進取。膽大飛翔,成就輝煌。努力進取,遙望,和諧家園??蓯塾巫?..
    趙原野閱讀 3,521評論 1 1
  • 在妖界我有個名頭叫胡百曉,無論是何事,只要找到胡百曉即可有解決的辦法。因為是只狐貍大家以訛傳訛叫我“傾城百曉”,...
    貓九0110閱讀 3,721評論 7 3

友情鏈接更多精彩內(nèi)容