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