uni-app文件上传下载
vue
<template>
<view>
<button @click="upload">上传</button>
<button @click="download">下载</button>
</view>
</template>
<script>
export default {
data() {
return {}
},
methods: {
upload: function() {
uni.chooseImage({
success: (chooseImageRes) => {
const tempFilePaths = chooseImageRes.tempFilePaths;
uni.uploadFile({
url: 'http://192.168.1.105/file/upload',
filePath: tempFilePaths[0],
name: 'file',
formData: {
'user': 'test'
},
success: (uploadFileRes) => {
console.log(uploadFileRes.data);
uni.showToast({
title: "上传成功",
icon: "ok"
});
}
});
},
fail: function(chooseImageRes) {
uni.showToast({
title: "取消上传",
icon: "none"
});
}
});
},
download: function() {
uni.downloadFile({
url: 'http://192.168.1.105/file/DWoVn7uIJZ6b07855d929239d528bd59a8a049b58ba1.jpg',
success: (res) => {
if (res.statusCode === 200) {
uni.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success: function() {
uni.showToast({
title: "保存成功",
icon: "ok"
});
},
fail: function() {
uni.showToast({
title: "取消保存",
icon: "none"
});
}
});
}
}
});
},
}
}
</script>
<style>
</style>
java
package com.cloud.controller;
import com.cloud.config.CloudConfigurer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
@RequestMapping("file")
@RestController
public class FileController {
@Autowired
private CloudConfigurer cloud;
@PostMapping("upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return "上传失败,请选择文件!";
}
String fileName = file.getOriginalFilename();
String filePath = this.cloud.getSavePath();
File dir = new File(filePath);
if (!dir.exists()) {
dir.mkdir();
}
try {
File file1 = new File(filePath, fileName);
file.transferTo(file1);
return (filePath + fileName);
} catch (IOException e) {
e.printStackTrace();
}
return "上传失败!";
}
}