文件上传下载 Blob格式存储

如何实现最基本的文件(附件)上传下载?

存储格式

数据库建立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)
  }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 以ASP.NET Core WebAPI作后端API,用Vue构建前端页面,用Axios从前端访问后端API ,包...
    jianshu1212阅读 924评论 0 0
  • 久违的晴天,家长会。 家长大会开好到教室时,离放学已经没多少时间了。班主任说已经安排了三个家长分享经验。 放学铃声...
    飘雪儿5阅读 7,592评论 16 22
  • 今天感恩节哎,感谢一直在我身边的亲朋好友。感恩相遇!感恩不离不弃。 中午开了第一次的党会,身份的转变要...
    迷月闪星情阅读 10,620评论 0 11
  • 可爱进取,孤独成精。努力飞翔,天堂翱翔。战争美好,孤独进取。胆大飞翔,成就辉煌。努力进取,遥望,和谐家园。可爱游走...
    赵原野阅读 2,796评论 1 1
  • 在妖界我有个名头叫胡百晓,无论是何事,只要找到胡百晓即可有解决的办法。因为是只狐狸大家以讹传讹叫我“倾城百晓”,...
    猫九0110阅读 3,361评论 7 3