uniapp+springboot批量上传附件

使用uniapp一次性上传多个附件,一次提交,避免使用for循环进行提交。本文只实现逻辑,没有进行代码及页面优化。

uniapp上传附件:建立上传按钮,并指定click事件,在click事件中调用如下代码:

uni.uploadFile();方法详细使用请参考官方文档:

uni.uploadFile(OBJECT) | uni-app官网

let token = getToken()
let header = {}
header.Authorization = 'Bearer ' +token;
uni.chooseFile({
	success: function (res) {
		let tempFilePaths = res.tempFilePaths
		let tempFiles = res.tempFiles
		let fileDatas = new Array();
		for(let i=0;i<tempFilePaths.length;i++){
			let obj = {};
			obj.name = tempFiles[i].name;
			// obj.file = tempFilePaths[i]
			obj.uri = tempFilePaths[i]
			fileDatas.push(obj)
		}
		uni.uploadFile({
			url: config.baseUrl + '/app/file/uploads', //仅为示例,非真实的接口地址
			files: fileDatas,
			// filePath: tempFilePaths[0],
			// name: 'file',
			header: header,
			formData: {
				'user': 'test'
			},
			success: (uploadFileRes) => {
				console.log(uploadFileRes.data);
			},
			fail: (err) => {
				console.log(err)
			}
		});
	}
});

 springboot后端controller

@PostMapping("/uploads")
    public AjaxResult uploadFiles(@RequestParam("user") String user, MultipartRequest files, HttpServletRequest request) throws Exception {

        try{
            String filePath = RuoYiConfig.getUploadPath();
            List<String> fileList = new ArrayList<>();
            AtomicReference<String> errMsg = new AtomicReference<>("");
            files.getMultiFileMap().forEach((key, multipartFiles) -> {
                MultipartFile file = multipartFiles.get(0);
                String fileName = null;
                try {
                    fileName = FileUploadUtils.multiUpload(filePath, file, key);
                    fileList.add(fileName);
                } catch (IOException e) {
                    errMsg.set(e.getMessage());
                }
            });
            if(StringUtils.isEmpty(errMsg.get())){
                return AjaxResult.success(fileList);
            }
            return AjaxResult.error(errMsg.get());

        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }

存储文件到服务器的核心代码:

file.transferTo("文件要存放的路径");
  • 7
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值