java阿里云上传图片

一笑奈何 提交于 2019-12-18 21:34:02

首先导入jar包,官方文档

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

然后创建一个类 UploadController

package cn.qingcheng.controller.file;

import cn.qingcheng.entity.Response;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
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 javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
public class UploadController {
    // 访问的域名
    private final String host = "oss-cn-shenzhen.aliyuncs.com";
    // 存储空间
    private final String bucketName = "xiaochi-img";

    /**
     * 阿里云存儲上传
     * @return
     */
    @PostMapping("/oss")
    public Response ossUpload(@RequestParam("file") MultipartFile file){
        // Endpoint以杭州为例,其它Region请按实际情况填写。
        String endpoint = "http://" + host;
        // 云账号AccessKey有所有API访问权限,建议遵循阿里云安全最佳实践,创建并使用RAM子账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建。
        String accessKeyId = "LTAI4Fh7azVyfYdzkkLZwSVU";
        String accessKeySecret = "m6iAuji31RjAUgKgDSWRxuCRUFTHIY";
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 上传文件流。
        // 保存路径,注意:这里不要以 / 或  \  开头
        String Path = "abc/" + new SimpleDateFormat("yyyy/MM").format(new Date()).toString();
        String originalFilename = file.getOriginalFilename();
        String fileName = Path + "/" + UUID.randomUUID().toString().replace("-","") + originalFilename.substring(originalFilename.lastIndexOf("."));
        try {
            ossClient.putObject(bucketName, fileName, file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 关闭OSSClient。
        ossClient.shutdown();
        Map map = new HashMap();
        map.put("url","https://" + bucketName + "." + host + "/" +fileName);
        return Response.success("上传成功",map);
    }

    /**
     * 上传本地图片
     * @param multipartFile
     * @param request
     * @return
     */
    @PostMapping("/native")
    private Response nativeUpload(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request){
        //String path = request.getSession().getServletContext().getRealPath("/img");
        String path = "D:\\web\\xampp\\htdocs\\images";
        String originalFilename = multipartFile.getOriginalFilename();
        String subPath = "/upload/" + new SimpleDateFormat("yyyy/MM").format(new Date()).toString();
        String fileName = path + "/" + subPath + "/" + UUID.randomUUID().toString().replace("-","") + originalFilename.substring(originalFilename.lastIndexOf("."));
        File file = new File(fileName);
        if (!file.getParentFile().exists()){
            file.setWritable(true);
            file.mkdirs();
        }
        try {
            multipartFile.transferTo(file);
        } catch (IOException e) {
            // e.printStackTrace();
            return Response.error("上传失败:"+e.getMessage());
        }
        Map map = new HashMap();
        map.put("url","http://images.com:8080" + subPath + "/" + file.getName());
        return Response.success("上传成功",map);
    }
}

如此就可以了。

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!