阿里云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 = "<yourAccessKeyId>";
	String accessKeySecret = "<yourAccessKeySecret>";
	String bucketName = "<yourBucketName>";

    /*
     * 图片上传
     * */
    @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()));
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值