阿里云oss的使用实现图片上传

1.引入oss依赖

<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>3.8.0</version>
</dependency>

2.引入图片上传依赖

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
</dependency>
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.3</version>
</dependency>

3.在mvc中配置上传解析器

<!--配置文件上传解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="defaultEncoding" value="UYF-8"/>
    <property name="maxUploadSize" value="500000"/>
</bean>

4.前段代码

<%@ page contentType="text/html;charset=UTF-8" language="java"  isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/user/quick14" method="POST" enctype="multipart/form-data">
    <input type="text" name="name" >
    <input type="file" name="file1">
    <input type="submit" name="提交">
</form>
<br>
<form action="${pageContext.request.contextPath}/user/quick15" method="POST" enctype="multipart/form-data">
    <input type="text" name="name" >
    <input type="file" name="file">
    <input type="submit" name="提交">
</form>
</body>
</html>

5.后端代码

package com.itheima.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.io.IOException;

@Controller
@RequestMapping("/user")
public class UserController {

	// Endpoint以杭州为例,其它Region请按实际情况填写。
	String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
	// 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。
	String accessKeyId = "";
	String accessKeySecret = "";
	String bucketName = "";

    /*
     * 图片上传
     * */
    @RequestMapping("/quick14")
    @ResponseBody
    public void quick14(String name, MultipartFile file1) throws IOException {
    	//oss对象
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        //图片名称
        String fileKey = "jiajia.jpg"; 
        //ByteArrayInputStream(file1.getBytes())将文件转为输入流
        ossClient.putObject(bucketName, fileKey, new ByteArrayInputStream(file1.getBytes()));
    }
}

你可能感兴趣的:(功能实现)