前言
這里我并沒有使用一些oss、七牛云等服務(wù)器上傳文件惰爬,而是采用的本地文件上傳喊暖,具體代碼如下:
后端
1、POM文件
<parent>
<artifactId>shangyou-parent</artifactId>
<groupId>com.cluck.video</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
</dependencies>
2撕瞧、application.yml文件
upload:
file-space: E:\code\My Code\app\upload ###你自己想存放的文件路徑
3陵叽、servie層
/** 文件上傳父目錄 */
@Value("${upload.file-space}")
private String fileSpace;
@Override
@Transactional
public ResponseVo uploadFace(String userId, MultipartFile[] files) throws IOException {
String token = redisTemplate.opsForValue().get(USER_REDIS_SESSION + ":" + userId);
if (StringUtils.isEmpty(token) || StringUtils.isEmpty(userId)) {
return ResponseVo.error("用戶id不能為空");
}
//數(shù)據(jù)庫(kù)相對(duì)路徑
String uploadPathDB = "/" + userId + "/face";
FileOutputStream outputStream = null;
InputStream inputStream = null;
String imageName = UUID.randomUUID().toString();
try {
if (files != null && files.length > 0) {
//文件名稱
String fileName = files[0].getOriginalFilename();
fileName = imageName + (fileName.substring(fileName.lastIndexOf(".")));
System.out.println("文件名稱:" + fileName);
if (StringUtil.isNotEmpty(fileName)) {
//最終路徑
String filePathFace = fileSpace + uploadPathDB + "/" + fileName;
System.out.println(filePathFace);
//數(shù)據(jù)庫(kù)保存路徑
uploadPathDB += ("/" + fileName);
File file = new File(filePathFace);
if (file.getParentFile() != null || file.getParentFile().isDirectory()) {
//創(chuàng)建父文件夾
file.getParentFile().mkdirs();
}
outputStream = new FileOutputStream(file);
inputStream = files[0].getInputStream();
IOUtils.copy(inputStream, outputStream);
}
} else {
return ResponseVo.error("上傳失敗~");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
outputStream.flush();
outputStream.close();
}
}
//TODO這里你可以把圖片地址保存到數(shù)據(jù)庫(kù)等等
return ResponseVo.success(uploadPathDB);
}
4、Controller層
@PostMapping("/uploadFace")
public ResponseVo uploadFace(String userId,
@RequestParam("file")MultipartFile[] files) throws IOException {
return usersService.uploadFace(userId, files);
}
5.配置類
@Configuration
public class WebConfig implements WebMvcConfigurer {
/** 文件上傳父目錄 */
@Value("${upload.file-space}")
private String fileSpace;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations("file:" + fileSpace + "/");
}
}
后端代碼主要是想從前端接收到用戶id丛版,然后把用戶id當(dāng)成每個(gè)用戶的文件目錄巩掺,
類似于E:\code\My Code\app\upload\557a99f2-48d0-4bb0-b076-8f950a3e042b\face
然后你就可以通過http://127.0.0.1:8080/557a99f2-48d0-4bb0-b076-8f950a3e042b\face\1.jpg訪問圖片了
小程序端代碼
- 小程序開發(fā)文檔 https://developers.weixin.qq.com/miniprogram/dev/framework/
- 從本地相冊(cè)選擇圖片或使用相機(jī)拍照API。https://developers.weixin.qq.com/miniprogram/dev/api/media/image/wx.chooseImage.html
- 將本地資源上傳到服務(wù)器API页畦。https://developers.weixin.qq.com/miniprogram/dev/api/network/upload/wx.uploadFile.html
- 發(fā)起 HTTPS 網(wǎng)絡(luò)請(qǐng)求API胖替。https://developers.weixin.qq.com/miniprogram/dev/api/network/request/wx.request.html
具體詳情可以參照小程序開發(fā)文檔
1、app.js
App({
serverUrl: "http://127.0.0.1:8080",
userInfo: null
})
2、upload.wxml
<image src="{{faceUrl}}" class="face" bindtap='changeFace'></image>
3独令、upload.js
const app = getApp()
Page({
faceUrl: '../resource/image/1.jpg', //默認(rèn)圖片地址
}),
//上傳文件
changeFace:function() {
//獲取全局變量
var me = this;
wx.chooseImage({//選擇文件
success (res) {
const tempFilePaths = res.tempFilePaths
wx.showLoading({
title: '上傳中...',
})
var user = app.userInfo
var serverUrl = app.serverUrl
//校驗(yàn)用戶id和圖片
if(user.id == null || tempFilePaths[0].length <= 0) {
wx.showToast({
title: '用戶id或圖片不存在~',
})
}
wx.uploadFile({//文件上傳
url: serverUrl +'/user/uploadFace?userId=' + user.id, //后端請(qǐng)求路徑
filePath: tempFilePaths[0],
name: 'file',
header: {
'content-type': 'application/json'
},
success (res){
var data = JSON.parse(res.data);
if(data.status == 0) {
wx.hideLoading();
wx.showToast({
title: '頭像上傳成功',
icon: 'success',
duration: 1500
})
me.setData({ // 設(shè)置圖片
faceUrl: serverUrl + data.msg
})
}
}
})
前端也都比較簡(jiǎn)單端朵,主要都是參考的api文檔那里也有具體示例,需要注意的就是文件上傳后success回調(diào)函數(shù)里data是個(gè)字符串燃箭,你需要把它轉(zhuǎn)為json也就是var data = JSON.parse(res.data);不然會(huì)出現(xiàn)undefined