上传文件至服务器

直接贴代码

public class UploadFileToService {

    public static String upload(MultipartFile file, String savePath) {
        // 新文件名长度
        int newFilenameLength = 16;
        // 新文件名组合类型
        int newFilenameType = RandomStringUtil.FIGURE_LOWER_CASE_POWER_CASE;
        // 新文件名
        String newFilename = RandomStringUtil.create(newFilenameLength, newFilenameType);
        try {
            File parentFile = new File(savePath);
            // 保存文件夹不存在则创建
            if (!parentFile.exists()) {
                parentFile.mkdirs();
            }
            // 获取真实的文件名
            String filename = file.getOriginalFilename();
            assert filename != null;
            // 文件后缀名
            String suffix = filename.substring(filename.lastIndexOf("."));
            InputStream inputStream = file.getInputStream();
            OutputStream outputStream = new FileOutputStream(savePath + File.separator + newFilename + suffix);
            // 复制文件至指定路径
            IOUtils.copy(inputStream, outputStream);
            // 清除缓存及关闭流
            outputStream.flush();
            outputStream.close();
            inputStream.close();
            // 返回文件路径
            return savePath + File.separator + newFilename + suffix;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

}

controller层:

@CrossOrigin
@RestController
@RequestMapping("test")
public class TestController {

    @PostMapping("test")
    private String test(@RequestParam("file") MultipartFile file) {
        ResultEntity resultEntity = new ResultEntity();
        try {
            // 文件的保存路径,这里以宝塔为例,需要文件夹的绝对路径,相对路径好像不太行
            String saveFile = "/www/server/tomcat/webapps/images";
            String result = UploadFileToService.upload(file, saveFile);
            ResultEntityEvent.successEvent(resultEntity, "上传文件成功!", result, 1);
        } catch (Exception e) {
            ResultEntityEvent.exceptionEvent(e, resultEntity, "上传文件出错啦,请查看后端日志!");
            e.printStackTrace();
        }
        return JsonTool.getJsonTool().toJson(resultEntity);
    }

}

uni-app调用

uni.showLoading({
    title: '文件上传中'
})
uni.chooseImage({
		count: 1,
		sizeType: 'compressed',
		success: (res) => {
			uni.uploadFile({
				url: '接口路径',
				filePath: res.tempFilePaths[0],
				name: 'file',
				success: (uploadFileRes) => {
					uni.hideLoading();
					console.log(uploadFileRes.data);
				}
			});
			res.tempFilePaths.forEach(function(item) {
				uni.downloadFile({
					url: item
				})
			})
		},
		fail: (data) => {}
})

h5端调用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传文件</title>
    <script type="text/javascript" src="/layui/layui.js"></script>
</head>
<body>

<input type="file" id="file">

<div type="button" id="btn">上传文件</div>

</body>
<script>

    // 如果不是用layui的话需要导入jquery.js
    const $ = layui.jquery;
    document.getElementById('btn').onclick = function () {
        const file = $('#file').get(0).files[0];
        console.log(file);
        const form_data = new FormData();
        form_data.append('file', file);
        $.ajax({
            url: '接口',
            type: 'POST',
            dataType: 'JSON',
            data: form_data,
            cache: false,
            processData: false,
            contentType: false,
            success: function (res) {
                console.log(res);
            },
            error: function (res) {
                console.log(res);
            }
        });
    }

</script>
</html>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

胡#

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值