java上传文件到minio

package com.nuzar.fcms.std.controller.std;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import com.nuzar.cloud.annotation.echo.EchoResult;
import com.nuzar.cloud.common.exception.BizException;
import com.nuzar.cloud.common.web.MassResult;
import com.nuzar.cloud.i18n.Messages;
import com.nuzar.cloud.oss.OssService;
import com.nuzar.cloud.utils.Assert;
import com.nuzar.cloud.web.controller.CommonController;
import com.nuzar.cloud.web.model.QueryModel;
import com.nuzar.common.security5.common.util.SecurityUtils;
import com.nuzar.fcms.std.constant.MessageCodes;
import com.nuzar.fcms.std.model.Attachments;
import com.nuzar.fcms.std.service.biz.IAttachmentsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.UUID;

/**
 * @description:
 * @author: zsy
 * @date: 2024/1/17 9:25
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/std/attachments")
public class AttachmentsController extends CommonController<Attachments, IAttachmentsService, QueryModel> {

    @Resource
    private OssService ossService;

    @EchoResult
    @PostMapping("/upload")
    public MassResult uploadAttachment(@RequestParam("file") MultipartFile file) {
        try {
            String name = file.getOriginalFilename();
            // 提取文件后缀
            String extName = FileUtil.extName(name);
            Assert.onI18n(ObjectUtil.isEmpty(extName), MessageCodes.STD_10062);
            extName = ".".concat(extName);
            String dateDir = DateUtil.format(new Date(), "yyyyMM");
            String buket = "fcms";
            String filePath = String.format("%s/%s_%s", dateDir,
                    SecurityUtils.getTenant(), UUID.randomUUID().toString().replace("-", "").concat(extName));
            ossService.put(buket, filePath, file.getInputStream());
            Thread.sleep(1000);
            return MassResult.success(filePath);
        } catch (Exception e) {
            log.error("upload file error", e);
            throw new BizException(Messages.i18n(MessageCodes.STD_10063));
        }
    }

    @EchoResult
    @PostMapping("/upload-db")
    public Attachments uploadAttachmentDb(@RequestParam("file") MultipartFile file) {
        try {
            String name = file.getOriginalFilename();
            // 提取文件后缀
            String extName = FileUtil.extName(name);
            Assert.onI18n(ObjectUtil.isEmpty(extName), MessageCodes.STD_10062);
            extName = ".".concat(extName);
            String dateDir = DateUtil.format(new Date(), "yyyyMM");
            String buket = "fcms";
            String filePath = String.format("%s/%s_%s", dateDir,
                    SecurityUtils.getTenant(), UUID.randomUUID().toString().replace("-", "").concat(extName));
            ossService.put(buket, filePath, file.getInputStream());
            Thread.sleep(1000);
            Attachments attachments = new Attachments();
            attachments.setBusinessId("");
            attachments.setName(filePath);
            this.getService().save(attachments);
            return attachments;
        } catch (Exception e) {
            log.error("upload file error", e);
            throw new BizException(Messages.i18n(MessageCodes.STD_10063));
        }
    }

    @GetMapping("/get-attachment")
    public void getPlanAttachment(@RequestParam("attachmentId") String attachmentId, HttpServletResponse response) {
        log.info("查看附件:{}", attachmentId);
        String buket = "fcms";
        Attachments attachments = this.getService().getById(attachmentId);
        String fileName = attachments.getName();
        String presignedLink = ossService.getPresignedLink(buket, fileName);
        log.info("file link:{}", presignedLink);
        InputStream inputStream = ossService.get(buket, fileName);
        try {
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes()));
            if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) {
                response.setHeader("content-type", "image/jpeg");
                response.setContentType("image/jpeg");
            } else if (fileName.endsWith(".png")) {
                response.setHeader("content-type", "image/png");
                response.setContentType("image/png");
            } else {
                response.setHeader("content-type", "application/octet-stream");
                response.setContentType("application/octet-stream");
            }

            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            byte[] b = new byte[1024];
            int i = 0;
            int length = 0;
            while ((i = inputStream.read(b)) != -1) {
                length = length + i;
                toClient.write(b, 0, i);
            }
            response.addHeader("Content-Length", "" + length);
            log.info("数据写出完成,length:{}", length);
            toClient.flush();
            toClient.close();

        } catch (Exception e) {
            log.error("download file fail", e);
        } finally {
            IOUtils.closeQuietly(inputStream);
        }
    }
}
package com.nuzar.fcms.std.model;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.nuzar.cloud.mapper.base.BaseEntity;
import lombok.Data;

/**
 * @description:
 * @author: zsy
 * @date: 2024/1/16 16:43
 */
@Data
@TableName("STD_ATTACHMENTS")
public class Attachments extends BaseEntity {

    @TableId(value = "id", type = IdType.ASSIGN_ID)
    private String id;

    @TableField("BUSINESS_ID")
    private String businessId;

    @TableField("NAME")
    private String name;

    @TableField("FILE_PATH")
    private String filePath;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值