pom文件
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId> <optional>true</optional>
</dependency>
<!-- mysql-connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.32</version>
</dependency>
后端utils代码
public class JesyFileUploadUtil {
/**
* 上传文件
*
* @param file --文件名
* @param serverUrl --服务器路径http://127.0.0.1:8080/ssm_image_server
* @return
* @throws IOException
*/
public static String uploadFile(MultipartFile file, String serverUrl) throws IOException {
//重新设置文件名
String newFileName = new Date().getTime()+""; //将当前时间获得的毫秒数拼接到新的文件名上
//随机生成一个3位的随机数
Random r = new Random();
for(int i=0; i<3; i++) {
newFileName += r.nextInt(10); //生成一个0-10之间的随机整数
}
//获取文件的扩展名
String orginalFilename = file.getOriginalFilename();
String suffix = orginalFilename.substring(orginalFilename.indexOf("."));
//创建jesy服务器,进行跨服务器上传
Client client = Client.create();
//把文件关联到远程服务器
//例如:http://127.0.0.1:8080/ssm_image_server/upload/123131312321.jpg
WebResource resource = client.resource(serverUrl+"/"+newFileName+suffix);
//上传
//获取文件的上传流
resource.put(String.class, file.getBytes());
//图片上传成功后要做的事儿
//1、ajax回调函数做图片回显(需要图片的完整路径)
//2、将图片的路径保存到数据库(需要图片的相对路径)
// String fullPath = serverUrl+"/upload/"+newFileName+suffix; //全路径
String relativePath = "/upload/"+newFileName+suffix; //相对路径
return relativePath;
}
}
Controller层
@RestController
@RequestMapping("/upload")
@CrossOrigin(origins = "*")
public class UploadController {
@PostMapping("/file")
public String uploadFile(MultipartFile fileName){
String path="";
try {
path = JesyFileUploadUtil.uploadFile(fileName, "http://localhost:8050/upload");
} catch (IOException e) {
e.printStackTrace();
}
return path;
}
}
前端上传文件函数
uploadLogo(){
//第1步:打开手机相册,或文件管理器选择文件
uni.chooseImage({
count:1,//允许上传一个文件
sizeType:['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
sourceType: ['album'], //从相册选择
success:function(res){
//获得选择好的文件,他是一个数组,就算只有一个文件,那也是数组中只有一个元素
const tempFilePaths = res.tempFilePaths;
//第2步:把选择的文件上传到服务器
_self.btnLoading = true //让上传按钮的进度条显示出来
_self.btnState = true //让上传按钮不可点击
const uploadTask = uni.uploadFile({
url:"http://localhost:8070/upload/file",
filePath:tempFilePaths[0],
name:"fileName",
success: (res) => {
console.log(res.data)
_self.btnLoading = false //让上传按钮的进度条显示出来
_self.btnState = false //让上传按钮不可点击
_self.formData.logoPath = res.data
}
})
//获取文件的上传进度
uploadTask.onProgressUpdate(function(res){
console.log("上传进度"+res.progress)
console.log("已经上传的数据长度"+res.totalBytesSent)
console.log("预计需要上传的数据总长度"+res.totalBytesExpectedToSend)
})
}
})
},