“This article has participated in the good article call order activity, click to see: back end, big front end double track submission, 20,000 yuan prize pool for you to challenge!”


preface

About Ali Cloud OSS I will not do too much introduction, want to know the small partner click the link below

Ali Cloud object storage OSS address

Ali Cloud object storage OSS development document address


1. Import OSS dependencies

<! -- Ali Cloud OSS-->
 <dependency>
     <groupId>com.aliyun.oss</groupId>
     <artifactId>aliyun-sdk-oss</artifactId>
     <version>3.10.2</version>
 </dependency>

 <! -- Date toolbar dependent -->
 <dependency>
     <groupId>joda-time</groupId>
     <artifactId>joda-time</artifactId>
     <version>2.9.3</version>
 </dependency>
Copy the code

2. Configure the configuration file

== Enter ali Cloud console (mouse can be seen on the head) ==

= = the endpoint: = =


3. Back-end code

==controller==

@RestController
@RequestMapping("/oss")
public class OssController {

    @Autowired
    private OssService ossService;

    // How to upload an image
    @PostMapping("policy/uploadAvator")
    public Result uploadOssFile(@RequestParam("file") MultipartFile file,
                                @RequestParam("module") String module) {
        // Obtain the uploaded MultipartFile
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String url = ossService.uploadFileAvatar(inputStream,module,file.getOriginalFilename());

        return Result.success("File uploaded successfully",url); }}Copy the code

OssService

public interface OssService {
    String uploadFileAvatar(InputStream inputStream, String module, String originalFilename);
}
Copy the code

OssServiceImpl

@Service
public class OssServiceImpl implements OssService {

    @Override
    public String uploadFileAvatar(InputStream inputStream,String module,String originalFilename) {
        // The utility class gets the value
        String endpoint = ConstantPropertiesUtils.END_POINT;
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;


        // Create an OSS instance
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        String folder = new DateTime().toString("yyyy/MM/dd");
        String fileName = UUID.randomUUID().toString();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        // Folder name in OSS
        String objectName = module + "/" + folder + "/" + fileName + fileExtension;

        // Create the meta information of the uploaded file. You can set the HTTP header with the meta information of the uploaded file.
        // If you do not set, directly access the URL will download the image itself, see you choose
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType("image/jpg");

        ossClient.putObject(bucketName, objectName, inputStream,objectMetadata);

        // Disable OSSClient.
        ossClient.shutdown();

        String url = "http://"+bucketName+"."+endpoint+"/"+objectName;
        returnurl; }}Copy the code

== The tool class obtains the value in the configuration file ==

@Component
public class ConstantPropertiesUtils implements InitializingBean {

    // Read the configuration
    @Value("${aliyun.oss.file.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.file.keyid}")
    private String keyid;

    @Value("${aliyun.oss.file.keysecret}")
    private String keysecret;

    @Value("${aliyun.oss.file.bucketname}")
    private String bucketname;


    // Define the exposed static constants
    public static String END_POINT;
    public static String ACCESS_KEY_ID;
    public static String ACCESS_KEY_SECRET;
    public static String BUCKET_NAME;

    @Override
    public void afterPropertiesSet(a) throws Exception { END_POINT = endpoint; ACCESS_KEY_ID = keyid; ACCESS_KEY_SECRET = keysecret; BUCKET_NAME = bucketname; }}Copy the code

4. Front-end code

Uploading component Code

  //action="https://jsonplaceholder.typicode.com/posts/"
 <el-upload
  class="avatar-uploader"
  action="Upload Address"
  :show-file-list="false"
  :on-success="handleAvatarSuccess"
  :before-upload="beforeAvatarUpload">
  <img v-if="tableData.avator" :src="tableData.avator" class="avatar">
  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
Copy the code

The callback function

HandleAvatarSuccess (res, file) {this.$message. Success(" Image modified successfully! "); ) this.imageUrl = URL.createObjectURL(file.raw); BeforeAvatarUpload (file) {const isLt2M = file.size / 1024/1024 < 10; if (! IsLt2M) {this.$message.error(' upload profile picture size cannot exceed 10MB! '); } return isLt2M; }Copy the code





The last

I am aCode pipi shrimpI am a mantis shrimp lover who loves to share knowledge. I will keep updating my blog in the future. I look forward to your attention!!

Creation is not easy, if this blog is helpful to you, I hope you can == a key three! ==, thanks for your support, see you next time ~~~

Share the outline

Big factory interview questions column