spring boot+uniapp上传单个文件
后端代码:文件上传位置为/static/photo目录下
@PostMapping("save")
public int savePicture(@RequestParam("file")MultipartFile file,@RequestParam("id")String id) throws IOException {
//如果文件不存在上传失败
if (file.isEmpty()) {
System.out.println("文件不存在");
return 0;
}
//获取文件名字
String fileName = file.getOriginalFilename();
//设置编译后文件存在路径
String path = ClassUtils.getDefaultClassLoader().getResource("").getPath()+"static/photo/";
//获取项目路径
File directory = new File("src/main/resources/static/photo");
String paths = directory.getCanonicalPath();
File dest = new File(paths+'/' + fileName);
System.out.println(dest.getAbsoluteFile());
FileInputStream fileInputStream = (FileInputStream) file.getInputStream();
//以流的方式上传
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path + File.separator + fileName));
byte[] bs = new byte[1024];
int len;
while ((len = fileInputStream.read(bs)) != -1) {
bos.write(bs, 0, len);
}
bos.flush();
bos.close();
try {
//文件上传
file.transferTo(dest);
return 1;
} catch (IOException e) {
}
return 1;
}
前端代码为
<template>
<view class="container">
<view>首页</view>
<view>上传文件测试</view>
<button type="primary" @click="uploadFile">点击上传文件</button>
</view>
</template>
<script>
export default {
data() {
return {
id:"20181008093"
}
},
methods: {
uploadFile(){
var _this=this;
uni.chooseImage({
success(res) {
console.log(res)
var tempFilePath=res.tempFilePaths;
uni.uploadFile({
url:'http://localhost:9000/save',
filePath:tempFilePath[0],
name:"file",
formData:{
"id":_this.id
},
success(res) {
console.log(res.data)
}
})
}
})
}
}
}
</script>
<style>
.container {
padding: 20px;
font-size: 14px;
line-height: 24px;
}
</style>
```html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构