vue中文件上传下载与回显

一.上传文件:

pc端

采用饿了么上传组件:<el-upload />

可以手动上传也可以立即上传

1.立即上传:

<el-upload
​
•            ref="myUpload"
​
•            :action="fileUploadApi + '?name=' + fileName"
​
•            :headers="headers" // 设置请求头{'Authorization': getToken()}
​
•            :on-error="uploadError"
​
•            :on-success="uploadSuccess"
​
•            :before-upload="uploadBefore" 
​
•            :on-change="uploadChange"
​
•            :on-remove="uploadRemove"
​
•            :file-list="fileList"
​
•            :auto-upload="true"
​
•          \>
​
•            <el-button slot="trigger" size="small" type="primary">附件上传</el-button>
​
•          </el-upload>

2.手动上传

一般点击确认按钮,监听这个按钮的点击事件,然后 this.$refs.myUpload.submit(),进行上传文件操作;

uploadSuccess方法监听文件上传成功的回调函数,接收三个回调参数,response, file, fileList,response是接口返回值,,

里面会返回服务器存放文件的id,把id存到表单对象里,最后做表单提交

移动端,vant组件里的<van-uploader />

Uploader 组件不包含将文件上传至服务器的接口逻辑,该步骤需要自行实现。

<van-uploader
​
•              @delete="onDelete"
​
•              v-model="fileList"
​
•              multiple
​
•              :after-read="afterRead"
​
•            />

文件上传完毕后会触发 after-read 回调函数,获取到对应的 file 对象。

data里定义fileId,用来存放上传文件返回的id
​
afterRead(*file*) {
​
•      // 此时可以自行将文件上传至服务器
​
•      console.log("file");
​
•      console.log(*file*);
​
•      *file*.status = "uploading";
​
•      *file*.message = "上传中...";
​
•      *const* fd = new *FormData*();
​
•      fd.append("files", *file*.file);
​
•      upload(fd)
​
•        .then(*res* *=>* {
​
•          *file*.status = "done";
​
•          *file*.message = "上传成功...";
​
•          // console.log(res.data[0], '文件上传');
​
•          this.fileId.push(*res*.data[0].id);
​
•        })
​
•        .catch(() *=>* {
​
•          // 上传失败
​
•          *file*.status = "failed";
​
•          *file*.message = "上传失败";
​
•        });
​
•    },
    onDelete(file, detail) {
      if (file.status == "failed") return;
      this.fileId.splice(detail.index, 1);
    },

二.文件下载

1.如果下载需要权限

export *function* downloadFile(*obj*, *name*, *suffix*) {
​
  *const* url = window.*URL*.createObjectURL(new *Blob*([*obj*]))
​
  *const* link = document.createElement('a')
​
  link.style.display = 'none'
​
  link.href = url
​
  *const* fileName = parseTime(new *Date*()) + '-' + *name* + '.' + *suffix*
​
  link.setAttribute('download', fileName)
​
  document.body.appendChild(link)
​
  link.click()
​
  document.body.removeChild(link)
​
}
​
downloadFile: function(id, name, suffix) {
  meetingApi.downloadAttach(id).then(res => {
    const blob = new Blob([res])
    const url = window.URL.createObjectURL(blob)
    const dom = document.createElement('a')
    dom.style.display = 'none'
    dom.href = url
    dom.setAttribute('download', name + '.' + suffix)
    document.body.appendChild(dom)
    dom.click()
  })
},

2.下载不需要权限,直接打开新网页的方式就行了

 window.location.href = `${process.env.VUE_APP_BASE_API}/api/localStorage/downloadFile/${id}`

三.文件回显

以移动端为例,

<van-uploader
 v-model="fileList"
 preview-size="75px"
 show-upload
 :deletable="false"
 @click-preview="clickPreview"
 >
  <div
 v-if="fileList.length === 0"
 style="color:#000;font-size:14px;"
 >
 附件无
  </div>
  <div v-else />
</van-uploader>

这里是监听父组件传过来的formdata对象,里面的fj字段存放文件的id,拿这个id去获取文件的信息

  
watch: {
    formData: {
      handler(newVal) {
        console.log(newVal);
        const fm = new FormData();
        fm.append("ids", newVal.fj);
        getFileStorage(fm).then(res => {
          if (!res.data) return;
          const resData = res.data;
          resData.map(item => {
            item.url = process.env.VUE_APP_BASE_API + item.url;
          });
          this.fileList = resData;
        });
      },
      immediate: true,
      deep: true
    }
  },

预览方法,如果是图片可以直接预览,其它类型文件需要借助其它的方法

clickPreview(file) {
      console.log("预览", file);
      // window.open("/editor/#/reader?fileId=xxx");
    }

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,请问您需要哪方面的帮助呢? 一般来说,vue可以使用axios或者fetch等ajax库发送文件请求,而springboot则可以使用Spring MVC的方式来处理上传文件请求。 上传文件的核心是FormData对象,可以使用它来构造包含文件数据的请求体。在vue,我们可以使用如下代码来上传文件: ``` <template> <div> <input type="file" ref="file" @change="handleFileChange"> <button @click="handleUpload">上传</button> </div> </template> <script> import axios from 'axios' export default { methods: { handleFileChange() { // 获取文件对象 this.file = this.$refs.file.files[0] }, handleUpload() { // 构造FormData对象 const formData = new FormData() formData.append('file', this.file) axios.post('/upload', formData, { headers: { 'Content-Type': 'multipart/form-data' } }) .then(response => { // 上传成功,处理回调 }) .catch(error => { // 上传失败,处理错误 }) } } } </script> ``` 在上面的代码,我们使用了input元素的type为file的属性来获取用户选择的文件,然后构造了一个含有文件数据的FormData对象,并使用axios库发送了post请求到服务器的/upload路径。注意需要设置请求头Content-Type为multipart/form-data。 在服务器端,我们可以使用Spring MVC的MultipartFile类型来接收文件。一个简单的springboot上传文件的代码示例: ``` import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; @RestController public class FileController { @PostMapping("/upload") public String upload(@RequestParam("file") MultipartFile file) { try { // 将文件保存到本地 file.transferTo(new File("保存路径")); // 返回上传成功的消息 return "上传成功!"; } catch (IOException e) { // 返回上传失败的消息 return "上传失败!"; } } } ``` 在上面的代码,我们使用了@PostMapping注解来接收POST请求,并使用@RequestParam注解来指定上传文件的参数名称。在方法内部,我们通过调用MultipartFile类型的transferTo方法来将文件保存到本地。注意需要处理文件保存失败的情况,并返回对应的消息。 至于如何将保存的文件回显到前端页面上,可以通过返回上传后的文件路径或者URL,并在前端页面上使用img或video等元素来显示文件。如果需要更加复杂的文件上传、处理、回显等操作,可以使用一些上传组件或者库来辅助完成。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值