아바타 수정 기능
com.aliyun.oss
aliyun-sdk-oss
2.8.3
public class AliOSSTest {
public static void main(String[] args) {
// Endpoint , Region 。
String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
// AccessKey API ,
String accessKeyId = "****";
String accessKeySecret = "****";
String bucketName = "****";
String filedir = "avatar/";
String fileKey = "hello.jpg";
// OSSClient
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
//
PutObjectResult putResult = ossClient.putObject(bucketName, filedir + fileKey, new File("D:\\bg.jpg"));
//
Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
// URL
URL url = ossClient.generatePresignedUrl(bucketName, filedir + fileKey, expiration);
System.out.println(url);
ossClient.shutdown();
}
}
package com.soft1721.jianyue.api.controller;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectResult;
import com.soft1721.jianyue.api.util.ResponseResult;
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;
import java.net.URL;
import java.util.Date;
import java.util.UUID;
@RestController
@RequestMapping(value = "/api")
public class UploadController {
@PostMapping("/avatar/upload")
public String ossUpload(@RequestParam("file") MultipartFile sourceFile) {
String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
String accessKeyId = "***";
String accessKeySecret = "***";
String bucketName = "***";
String filedir = "avatar/";
//
String fileName = sourceFile.getOriginalFilename();
//
String suffix = fileName.substring(fileName.lastIndexOf("."));
//uuid
String prefix = UUID.randomUUID().toString();
//
String newFileName = prefix + suffix;
//File
File tempFile = null;
try {
// , uuid +
tempFile = File.createTempFile(prefix, prefix);
// MultipartFile File
sourceFile.transferTo(tempFile);
} catch (IOException e) {
e.printStackTrace();
}
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
ossClient.putObject(bucketName, filedir + newFileName, tempFile);
Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
// URL
URL url = ossClient.generatePresignedUrl(bucketName, filedir + newFileName, expiration);
ossClient.shutdown();
//URL
return url.toString();
}
}
@PostMapping("/avatar")
public String ossUpload(@RequestParam("file") MultipartFile sourceFile,@RequestParam("userId") int userId) {
String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
String accessKeyId = "***";
String accessKeySecret = "***";
String bucketName = "***";
String filedir = "avatar/";
//
String fileName = sourceFile.getOriginalFilename();
//
String suffix = fileName.substring(fileName.lastIndexOf("."));
//uuid
String prefix = UUID.randomUUID().toString();
String newFileName = prefix + suffix;
File tempFile = null;
try {
//
tempFile = File.createTempFile(prefix, prefix);
// MultipartFile to File
sourceFile.transferTo(tempFile);
} catch (IOException e) {
e.printStackTrace();
}
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
ossClient.putObject(bucketName, filedir + newFileName, tempFile);
Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
// URL
URL url = ossClient.generatePresignedUrl(bucketName, filedir + newFileName, expiration);
ossClient.shutdown();
// userId
User user = userService.getUserById(userId);
//
user.setAvatar(url.toString());
//
userService.updateUser(user);
// ,
return url.toString();
}
3. 프런트엔드
data() {
return {
nickname: uni.getStorageSync('login_key').nickname,
avatar: uni.getStorageSync('login_key').avatar,
userId: uni.getStorageSync('login_key').userId
};
}
var _this = this;
uni.showActionSheet({
itemList: [' ', ' '],
success: function(res) {
console.log(' ' + (res.tapIndex + 1) + ' ');
//
if (res.tapIndex == 0) {
uni.chooseImage({
count: 1,
sourceType: ['camera'],
success: function(res) {
uni.saveImageToPhotosAlbum({
filePath: res.tempFilePaths[0],
success: function() {
console.log('save success');
uni.uploadFile({
url: 'http://****:8080/api/user/avatar',
filePath: res.tempFilePaths[0],
name: 'file',
formData: {
userId: _this.userId
},
success: uploadFileRes => {
console.log(uploadFileRes.data);
_this.avatar = uploadFileRes.data;
}
});
}
});
}
});
}
//
if (res.tapIndex == 1) {
uni.chooseImage({
count: 1, // 9
sizeType: ['original', 'compressed'], // ,
sourceType: ['album'], //
success: function(res) {
console.log(JSON.stringify(res.tempFilePaths));
uni.uploadFile({
url: 'http://******:8080/api/user/avatar',
filePath: res.tempFilePaths[0],
name: 'file',
formData: {
userId: _this.userId
},
success: uploadFileRes => {
console.log(uploadFileRes.data);
_this.avatar = uploadFileRes.data;
}
});
}
});
}
},
fail: function(res) {
console.log(res.errMsg);
}
});
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.