vue.js+Springboot实现文件自定义上传

vue.js+ElementUI+Springboot实现文件自定义上传

1、文件上传
文件上传使用的是elementUI组件,详情请点击链接elementUI文件上传组件
前端代码

<div style="height:100px;width:770px;overflow: hidden;text-align:left">
  <div style="overflow-y: scroll;height:180px;width:787px;">
    <el-upload ref="upload" 
    :multiple="true" 
    :auto-upload="false" 
    :on-change="handleChange"
    :file-list="fileList" 
    :on-remove="handleRemove" 
    :http-request="uploadFile" 
    style="height:100px" 
    action="String" >                  
    <el-button slot="trigger" size="small" type="primary">选择文件</el-button>                           
    <el-button :disabled="isButtonDisabled" style="margin-left: 30px;" size="small"    
    type="primary" @click="submitUpload">确定上传</el-button> 
    </el-upload>              
  </div>            
</div>

简单介绍下组件用到的各个属性以及方法:
1、:multiple:是否支持文件多选。
2、:auto-upload:是否在选取文件后立即上传
3、:on-change:文件状态改变时的钩子,添加文件、上传成功和上传失败时都会被调用,我这里用于对上传文件格式的判断。
4、:file-list:上传文件的列表。
5::on-remove:文件列表移除文件时的钩子。
6、:http-request:覆盖默认的上传行为,自定义上传需要添加这个属性。
7:action:必选参数,上传的地址(如果要自定义上传此参数也必须有,只不过给他随便赋个值就行)

我这里实现自定义上传的方法为uploadFile这个方法


  uploadFile() {      
    const formData = new FormData()
    this.fileList.forEach(element => {        
    if (element.status !== 'success') {          
    formData.append('reportFile', element.raw, element.raw.name)        
    }      
    })            
    formData.append('userName', this.psnName)           
    uploadReport(formData).then(data => {        
    this.fileList.forEach(element => {          
      element.status = 'success'        
     })        
    this.$message({          
    message: '文件上传成功!',          
    type: 'success'        
    })             
    }).catch(response => {        
    this.$message.error('文件上传失败!')      
    })    
  }

上传的文件以及其他参数都需要放在formData中,uploadReport为请求后端就扣的api。

export function uploadReport(formData) {  
 return request({    
   url: '/tagManage/uploadQualityReport',    
   method: 'post',    
   data: formData  
   })
 }

点击确认上传按钮,调用uploadFile方法请求后端。
以上就是文件上传的前端核心代码。

2、后端代码

@RequestMapping("/uploadReport")
 public void uploadReport(MultipartFile[] reportFile, HttpServletRequest request,String userName) {
  /**
   * 上传代码
   */
  for (MultipartFile multipartFile : reportFile) {
   String fileName = multipartFile.getOriginalFilename();
   String filePath = "你要上传的地址“
   File  targetFile = new File(filePath);
   if (!targetFile.exists()) {
    targetFile.mkdirs();
   }
   File dest = new File(filePath + fileName );
   try {
    multipartFile.transferTo(dest);
   catch (IOException e) {
    logger.error(e.getMessage());
    throw new BaseException(PurchaseExceptionCode.文件上传错误);
   }
  }
 }

以上就是文件上传的前后端代码,如有不足之处,请多多指教,有不明白的地方也可以评论留言,感谢。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值