아바타 수정 기능

8858 단어
1. 개발 전 준비
  • 아리운에서 AccessKey ID, Access Key 시크릿을 신청하여 잘 보관
  • 아리운 OSS 신청, 신규 Bucket, 디렉터리, 직접 사진 두 장 올리기 먼저 해보기
  • 2. 백엔드 인터페이스 개발
  • pom 의존 추가
  • 
        com.aliyun.oss
        aliyun-sdk-oss
        2.8.3
    
    
  • 첫 번째 테스트 프로그램, 아리운 OSS 업로드 기능 테스트
  • 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();
        }
    }
    
  • 업로드 인터페이스 프로그램을 작성하고 swagger 테스트
  • 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();
        }
    }
    
  • UploadController
  • @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. 프런트엔드
  • setting 페이지에서 사용자 자료를 클릭하여 user 로 이동info 페이지, 페이지에서 잊지 마세요.json 새 페이지 등록
  • 
        
    
    
  • user_info 페이지에서 이미지 클릭 이벤트를 하고 ActionSheet
  • 을 누르면 팝업
    
    
  • js 부분의 데이터 데이터
  • data() {
    return {
    nickname: uni.getStorageSync('login_key').nickname,
    avatar: uni.getStorageSync('login_key').avatar,
    userId: uni.getStorageSync('login_key').userId
    };
    }
    
  • showActionSheet 함수
  •    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);
                    }
                });
            }
    

    좋은 웹페이지 즐겨찾기