uniapp springboot 上传demo
前端
<template>
<view class="container">
<button type="primary" @click="chooseVideo">选择视频</button>
<video v-if="localUrl" :src="localUrl" controls></video>
<view style="margin-bottom: 40rpx;"></view>
<button type="warn" @click="uploadVideo" :disabled="!localUrl">上传视频</button>
</view>
</template>
<script>
export default {
data() {
return {
localUrl: ''
};
},
methods: {
chooseVideo() {
uni.chooseVideo({
success: (res) => {
this.localUrl = res.tempFilePath;
}
});
},
uploadVideo() {
if (!this.localUrl) {
uni.showToast({
title: '请先选择视频',
icon: 'none'
});
return;
}
uni.uploadFile({
url: 'http://127.0.0.1:9035/web/sms/test02', // 替换为你的服务器地址
filePath: this.localUrl,
name: 'file',
formData: {
'user': 'test'
},
success: (uploadRes) => {
console.log('上传成功', uploadRes.data);
uni.showToast({
title: '上传成功'
});
},
fail: (err) => {
console.error('上传失败', err);
uni.showToast({
title: '上传失败',
icon: 'none'
});
}
});
}
}
};
</script>
<style scoped>
/* Add your styles here */
</style>
后端
private static final String UPLOAD_DIR = "d:/logs/uploads/"; @SneakyThrows @PostMapping("/test02") public ResponseEntity<String> test02(@RequestParam("file") MultipartFile file) { if (file.isEmpty()) { return ResponseEntity.badRequest().body("Please select a file to upload."); } // Create the uploads directory if it doesn't exist File uploadDir = new File(UPLOAD_DIR); if (!uploadDir.exists()) { uploadDir.mkdirs(); } // Save the file on the server byte[] bytes = file.getBytes(); Path path = Paths.get(UPLOAD_DIR + file.getOriginalFilename()); Files.write(path, bytes); return ResponseEntity.ok("You successfully uploaded " + file.getOriginalFilename() + "!"); }