栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

minio服务器在win10的上传与下载,以及修改头像Minio速看

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

minio服务器在win10的上传与下载,以及修改头像Minio速看

首先自己配置Minio服务器 和客户端 请点击 官网地址http://www.minio.org.cn

安装完成后自己百度win10安装。

我是用Spring boot 配置 首先导入 Minio Dependency配置

        
        
            io.minio
            minio
            8.3.0
        

        
            me.tongfei
            progressbar
            0.5.3
        

        
            com.squareup.okhttp3
            okhttp
            4.8.1
        

接着配置yml (yml的配置一定要对齐!!!!!) #号代表注释

minio:
  #minio服务器配置
  endpoint: http://127.0.0.1:9002  //Minio服务器端口
  #minio服务器配置账号
  accessKey: 自己配置的账号
  #minio服务器配置密码
  secretKey: 自己配置的密码
  #minio服务器桶
  bucketName: 自己设置的桶名

我的Minion客户端界面:

接下来是我的:controller层代码

import com.alibaba.fastjson.JSON;
import com.dlsp.server.pojo.RespseBean;
import io.minio.*;
import io.minio.messages.Item;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.*;

@RestController
@RequestMapping("/system/init")
public class MinioController {

    @Autowired
    private MinioClient minioClient;

    @Value("${minio.bucketName}")
    private String bucketName;

    @ApiOperation(value = "查看文件集")
    @GetMapping("/minioList")
    public List list() throws Exception {
        //获得bucket列表
        Iterator> iterator = MyMinioLists().iterator();
        List items = new ArrayList<>();
        String format = "{'fileName':'%s','fileSize':'%s'}";
        while (iterator.hasNext()) {
            Item item = iterator.next().get();
            items.add(JSON.parse(String.format(format, item.objectName(), formatFileSize(item.size()))));
        }
        return items;
    }

    
    public Iterable> MyMinioLists() {
        Iterable> myObejcts = minioClient.listObjects(
                ListObjectsArgs
                        .builder()
                        .bucket(bucketName)
                        .build()
        );
        return myObejcts;
    }

    @ApiOperation(value = "删除文件")
    @DeleteMapping("/minioDelete/{fileName}")
    public RespseBean delete(@PathVariable("fileName") String fileName) {
        try {
            minioClient.removeObject(
                    RemoveObjectArgs
                            .builder()
                            .bucket(bucketName)
                            .object(fileName)
                            .build()
            );
        } catch (Exception e) {
            e.printStackTrace();
            return RespseBean.error("删除失败");
        }
        return RespseBean.success("删除成功");
    }

    @ApiOperation("文件上传(多)")
    @PostMapping("/minioUpload")
    public RespseBean upload(@RequestBody MultipartFile[] file) {  //多文件上传
        if (file == null || file.length == 0) {
            return RespseBean.error("上传文件不能为空");
        }
        List orgFileNameList = new ArrayList<>(file.length);
        for (MultipartFile multipartFile : file) {
            String orgfileName = multipartFile.getOriginalFilename();  //获得文件的原始名称;
            orgFileNameList.add(orgfileName);
            InputStream in = null;
            try { //文件上传
                in = multipartFile.getInputStream();
                minioClient.putObject(
                        PutObjectArgs
                                .builder()
                                .bucket(bucketName)
                                .object(orgfileName)
                                .stream(in, multipartFile.getSize(), -1)
                                .contentType(multipartFile.getContentType())
                                .build()
                );
            } catch (Exception e) {
                return RespseBean.error("文件上传失败");
            } finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        Map data = new HashMap();
        data.put("bucketName", bucketName);
        data.put("fileName", orgFileNameList);
        return RespseBean.success("添加成功", data);
    }

    //@PathVariable主要用于接收http://host:port/path/{参数值}数据。
    // @RequestParam主要用于接收http://host:port/path?参数名=参数值数据.
    @ApiOperation("文件下载")
    @GetMapping(value = "/minioDownload/{fileName}", produces = "application/octet-stream")
    public void downLoad(HttpServletResponse response, @PathVariable("fileName") String fileName) {
        InputStream in = null;
        try {
            //根据文件名获得对象
            StatObjectResponse stat = minioClient.statObject(
                    StatObjectArgs
                            .builder()
                            .bucket(bucketName)
                            .object(fileName)
                            .build()
            );
            response.setContentType(stat.contentType());
            //设置浏览器链接 下载文件
            response.setHeader("content-type", "application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            //根据对象 -->  文件下载
            in = minioClient.getObject(
                    GetObjectArgs
                            .builder()
                            .bucket(bucketName)
                            .object(fileName)
                            .build()
            );
            IOUtils.copy(in, response.getOutputStream());
        } catch (Exception e) {
        } finally {
            if (in != null) {
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    
    private static String formatFileSize(long fileS) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        String wrongSize = "0B";
        if (fileS == 0) {
            return wrongSize;
        }
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + " B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) (fileS >> 10)) + " KB";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) (fileS >> 20)) + " MB";
        } else if (fileS > 1073741824) {
            fileSizeString = df.format((double) (fileS >> 30)) + " GB";
        }
        return fileSizeString;
    }
 

我直接在Controller做完了所有
接下来是我在前端Vue +饿了么-Ui做的管理
自己根据导入的jar包 去官方文档 Minioclient 去使用具体的方法
SDK方法区:(自己看)
链接https://docs.min.io/docs/java-client-quickstart-guide.html
我的前端VUE






展示图:

这是我简单的就是文件CRUD
接下来是: 保存服务器文件并生成网络路径 存放在在Mysql 当中 和修改头像功能

修改管理员的头像 Controller层:

import com.dlsp.server.pojo.Admin;
import com.dlsp.server.pojo.RespseBean;
import com.dlsp.server.service.IAdminService;
import io.minio.*;
import io.minio.http.Method;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.concurrent.TimeUnit;


@RestController
public class AdminInfoController {

    @Autowired
    private IAdminService adminService;

    @Autowired
    private MinioClient minioClient;

    @Value("${minio.bucketName}")
    private String bucketName;

    
    @ApiOperation(value = "更新用户当前信息")
    @PutMapping("/admin/net")
    public RespseBean updateAdminInfo(@RequestBody Admin admin, Authentication authentication) {
        if (adminService.updateById(admin)) {
            SecurityContextHolder.getContext().setAuthentication
                    (new UsernamePasswordAuthenticationToken(admin, null, authentication.getAuthorities()));
            return RespseBean.success("adminIfo:修改用户信息成功");
        }
        return RespseBean.error("adminIfo:修改用户信息失败");
    }

    
    @ApiOperation(value = "更新用户密码")
    @PutMapping("/admin/pass")
    public RespseBean updateAdminPassword(@RequestBody Map info) {
        String oldPass = (String) info.get("oldPass");
        String pass = (String) info.get("pass");
        Integer adminId = (Integer) info.get("adminId");
        return adminService.updateAdminPassword(oldPass, pass, adminId);
    }

    
    @ApiOperation(value = "更新头像")
    @PostMapping("/admin/userFace")
    public RespseBean updateAdminFase(MultipartFile file, Integer id, Authentication authentication) {
        if (file == null || file.isEmpty()) {
            return RespseBean.error("上传文件不能为空");
        }
        InputStream in = null;
        String orgfileName = file.getOriginalFilename(); //获取文件名
        System.out.println("文件名" + orgfileName);
        Map reqParams = new HashMap();
        reqParams.put("response-content-type", "image/png");
        String url = "";
        try {
            in = file.getInputStream();
            minioClient.putObject(
                    PutObjectArgs
                            .builder()
                            .bucket(bucketName)
                            .object(orgfileName)
                            .stream(in, file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build()
            );
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        BucketExistsArgs bucketExistsArgs = BucketExistsArgs.builder().bucket(bucketName).build();
        Integer expires = 604800;
        try {
            boolean flag = minioClient.bucketExists(bucketExistsArgs);
            if (flag) {
                GetPresignedObjectUrlArgs getPresignedObjectUrlArgs = GetPresignedObjectUrlArgs
                        .builder()
                        .method(Method.GET)
                        .bucket(bucketName)
                        .object(orgfileName)
                        .expiry(expires)
                        .build();
                url = minioClient.getPresignedObjectUrl(getPresignedObjectUrlArgs);
                System.out.println(url);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return adminService.updateUserFace(url, id, authentication);
    }


}
Service修改头像:

```java
    
    @Override
    public RespseBean updateUserFace(String url, Integer id, Authentication authentication) {
        Admin admin = adminMapper.selectById(id);
        admin.setUserface(url);
        int result = adminMapper.updateById(admin);
        if(1 == result){
            Admin principal = (Admin) authentication.getPrincipal();
            principal.setUserface(url);
            SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(admin,null,authentication.getAuthorities()));
            return RespseBean.success("修改用户头像成功");
        }
        return RespseBean.error("更新失败!");
    }
头像在数据库只能保存7天,7天后过期,再次上传。
  前端Vue展示:
  

```javascript
  
                        
                    

这就是我大致的Minio 所做的操作
下面是我的数据库:
varchar 255不够 生成的图片链接用400即可.
《 !!这是我生成的本地图片地址 以为我没买服务器嘻嘻。
http://127.0.0.1:9002/lqs/%E5%9B%BE1.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=sharkdidi%2F20211222%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20211222T023153Z&X-Amz-Expires=604800&X-Amz-SignedHeaders=host&X-Amz-Signature=43e13eb3b0b9386ca627ae7205714c67e5d2f078e562b7a10165a51b8a0eb318

谢谢大嘎 全是干货 点!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号