代码编织梦想

 <!--阿里oss-->
        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>2.4.0</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>

工具类

import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import lombok.Getter;
import lombok.Setter;
import org.springframework.stereotype.Component;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

@Getter
@Setter
@Component
public class OssUtil {

    private static String endpoint = "oss-cn-hangzhou.aliyuncs.com";
    private static String accessKeyId = "需要申请";
    private static String accessKeySecret = "需要申请";
    private static String bucketName = "需要申请";


    public static OSSClient client;
    public OSSClient initClient(){
        if(null==client){
            ClientConfiguration conf = new ClientConfiguration();
            conf.setConnectionTimeout(5000);
            conf.setMaxErrorRetry(10);
            client = new OSSClient("http://" + endpoint, accessKeyId, accessKeySecret,conf);
        }
        return client;
    }

    public boolean putObjectForInputStream(String fileKey, InputStream content) {
        if (null == fileKey || "" == fileKey.trim())
            return false;
        try {
            initClient();
            ObjectMetadata meta = new ObjectMetadata();
            meta.setContentType("image/jpg");
            client.putObject(bucketName, fileKey, content, meta);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
 

    public  String  putObjectForImage(String imageName, InputStream content, boolean if400) {
        if (null == imageName || "" == imageName.trim())
            return null;
        try {
            String file = "images/" + imageName.substring(0, imageName.indexOf(".")) + "/" + imageName;
            putObjectForInputStream(file,content);
            return "http://"+bucketName+"."+endpoint+"/"+file;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 
 
    public String getObject(String key) {
        try {
            OSSObject object = client.getObject(bucketName, key);
            InputStream objectContent = object.getObjectContent();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int i = -1;
            while ((i = objectContent.read()) != -1) {
                baos.write(i);
            }
            objectContent.close();
            return baos.toString("UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 
 //上传文件使用这个
  public static  String upload(File file){


        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = format.format(new Date());

        if(null == file){
            return null;
        }

        OSSClient ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);
        try {
            //容器不存在,就创建
            if(! ossClient.doesBucketExist(bucketName)){
                ossClient.createBucket(bucketName);
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                ossClient.createBucket(createBucketRequest);
            }
            //创建文件路径
            String fileUrl = "image"+"/"+(dateStr + "/" + UUID.randomUUID().toString().replace("-","")+"-"+file.getName());
            //上传文件
            PutObjectResult result = ossClient.putObject(new PutObjectRequest(bucketName, fileUrl, file));
            //设置权限 这里是公开读
            ossClient.setBucketAcl(bucketName,CannedAccessControlList.PublicRead);
            if(null != result){
                log.info("==========>OSS文件上传成功,OSS地址:"+fileUrl);
                return "http://mawm.oss-cn-hangzhou.aliyuncs.com/"+fileUrl;
            }

//            //返回图片所在的全部路径,方便前端访问
//            //设置过期时间为100年
//            Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
//            // 生成URL
//            //endpoint,accessKeyId,accessKeyId就不说了  我上个博客说了
//            //这些都是一样的
//            OSSClient ossClient1 = new OSSClient(endpoint, accessKeyId, accessKeyId);
//            //这里得到的url就是图片的全路径
//            URL url = ossClient.generatePresignedUrl(bucketName, fileUrl, expiration);
//            if(null != url){
//                log.info("==========>OSS文件上传成功,OSS地址:"+url.toString());
//                return url.toString();
//            }


        }catch (OSSException oe){
            log.error(oe.getMessage());
        }catch (ClientException ce){
            log.error(ce.getMessage());
        }finally {
            //关闭
            ossClient.shutdown();
        }
        return null;
    }
 
    public static void main(String[] args) {
        try {
            //String text = "<p><br/><br/>雪纺印花百褶裙半身裙,简约的线条和版型上身很好看,整体更有看点。时尚真皮女凉鞋 牛筋底中跟欧美潮鞋 2015夏个性森系女鞋子罗马鞋。</p><p><img src=\"/manager/plugins/ueditor/jsp/upload1/20160129/99731454031866641.png\"/></p>";
            //String s = OssUtil.uploadTextImg(text);
 
 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
}

    /**
     * 上传图片
     *
     * @param file
     * @return
     */
    @SneakyThrows
    @PostMapping("/upLoadHeader")
    public String upLoadPicture(@RequestParam("file") MultipartFile file) {
        InputStream inputStream = null;
        try {

            byte[] byteArr = file.getBytes();
            inputStream = new ByteArrayInputStream(byteArr);
            String fileName = file.getOriginalFilename();
            String fileUUid = UUID.randomUUID().toString().replace("-","");
            fileName = fileUUid + "." + fileName.split("\\.")[1];
            String upload = ossUtil.putObjectForImage(fileName, inputStream, false);

            return upload;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
            return e.getMessage();
        } finally {
            inputStream.close();
        }

    }
	//上传文件
    @RequestMapping("/updateOssFile")
    public String updateOssFile(MultipartFile file) {
        try {

            if(null != file){
                //获取文件的名字
                String filename = file.getOriginalFilename();
                //  System.out.println("filename"+filename);
                if(!"".equals(filename.trim())){
                    File newFile = new File(filename);
                    FileOutputStream os = new FileOutputStream(newFile);
                    os.write(file.getBytes());
                    os.close();
                    file.transferTo(newFile);
                    //上传到OSS
                    String upload = AliyunOSSUtil.upload(newFile);

                    //上传到oss后,删除遗留在项目中的文件
                    String path = System.getProperty("user.dir");
                    String filepath=path+File.separator+file.getOriginalFilename();
                    File file1=new File(filepath);
                    if(file1.exists())
                    {
                        file1.delete();
                    }else {
                        log.info("============>删除oos上传服务器之后,遗留在项目中的文件失败");
                    }
                    return upload;
                }

            }
        }catch (Exception ex){
            ex.printStackTrace();
        }

        return "1";

    }

下面是上传文件到本地:
工具类

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

public class UploadImgUtil {


    public static String uploadImg(MultipartFile file) throws IOException {
        //2.根据时间戳创建新的文件名,这样即便是第二次上传相同名称的文件,也不会把第一次的文件覆盖了
        String fileName = System.currentTimeMillis() + file.getOriginalFilename();
        //3.通过req.getServletContext().getRealPath("") 获取当前项目的真实路径,然后拼接前面的文件名
        //String destFileName = "C:\\HBuilderX\\HBuilderProjects\\TP\\"+fileName;
        // String destFileName = ResourceUtils.getURL("classpath:").getPath()+"/static/"+fileName;
        String destFileName = System.getProperty("user.dir")+"/static/"+fileName;
        //4.第一次运行的时候,这个文件所在的目录往往是不存在的,这里需要创建一下目录(创建到了webapp下uploaded文件夹下)
        File destFile = new File(destFileName);
        destFile.getParentFile().mkdirs();
        //5.把浏览器上传的文件复制到希望的位置
        file.transferTo(destFile);
        //6.把文件名放在model里,以便后续显示用
        return "/static"+"/"+fileName;
    }
}

具体调用

  //上传文件返回文件地址
    @RequestMapping("/updateFile")
    public String updateFile(MultipartFile file) throws IOException {
        if (null == file){
            return "没有传输文件";
        }
        String s = UploadImgUtil.uploadImg(file);
        return s;
    }
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_40951656/article/details/127996906

阿里oss文件上传记录-爱代码爱编程

<!--阿里云对象存储服务--> <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId>

阿里云OSS文件存储-爱代码爱编程

1、引入阿里云OSS的pom依赖 <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId>

阿里 OSS 文件上传,别再说你不会上传文件了。-爱代码爱编程

J3 - 白起OSS(文件上传 # 教程) 最近关注我的都知道,我开了一个 communication(地址) 项目,本意是将它开发成一个多功能系统中台,所以为其量身打造了很多个功能,可以说都快成一个大杂烩了被我搞得。 但我发现这个项目连基本的文件上传都没有,这不行,要搞一个。 在进行文件上传功能前,我分析了一下腾讯及阿里的文件存储服务功能,流

阿里云oss文件存储-爱代码爱编程

首先添加依赖 <!--阿里云文件管理服务--> <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> </dependency> 然后

阿里云oss存储文件上传功能实现-爱代码爱编程

阿里云oss文件上传 分布式文件系统 分布式文件存储、 常用分布式文件存储,Fastdfs和GDFS 需要购买服务器进行额外的搭建成本较高。推荐使用阿里的oss降低学习的成本。 与此对应的还有搭建FTP服务器等。 开通oss服务 根据官网的提示开通oss服务。 创建Bucket 参考文档进行学习 使用springboot工程整合阿里云

阿里云的文件oss文件存储对象_weixin_43886588的博客-爱代码爱编程

阿里云的文件oss文件存储对象 01、实现具体的步骤 01、注册阿里云的服务账号 02、选择阿里云产品oss服务 03、创建一个Bucket文件存储桶 04、java对接oss服务 导入oss的sdk依赖 <dependency> <groupId>com.aliyun.oss</groupId>

阿里云oss存储_edward_hjh的博客-爱代码爱编程

官方文档:https://help.aliyun.com/document_detail/31817.html 访问Oss文件方式:restful API 1,文件存储类型 2,领域模型 3,重要特性 4,使用方式 官方文档:https://help.aliyun.com/document_detail/31817.html 访问Oss文件方式:restf

大规模文件存储怎么办?10分钟学会阿里oss对象存储_马剑威老师的博客-爱代码爱编程

一. 前言 最近有很多小伙伴问健哥,如果我们要进行大规模的文件存储该怎么做? 其实实现文件存储的技术有很多,如果我们在网上搜索一下,你会发现实现的技术简直是五花八门,比如有一种技术叫FastDFS就可以实现文件存储,但该方案需要自己搭建服务器,非常的麻烦。 实际上现在很多公司都在使用腾讯云或者阿里云技术,比如阿里云就提供了OSS对象存储技术,该技术安