springcloud miniio实现文件上传下载预览删除-调用miniio

spring框架里调用miniio

概述过程

首先项目框架中配好miniio
调用miniio方法,传正确参数

方法

上传

/**
     * 上传文件
     * 文件名采用uuid,避免原始文件名中带"/"符号导致下载的时候解析出现异常
     *
     * @param file   资源
     * @param dir    文件夹 (前后不带/)
     * @param rename 是否重命名 默认true
     * @return R(bucketName, filename, fullName)
     */
    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Resp<FileStatVo> upload(@RequestPart("file") MultipartFile file,
                                   @RequestParam(required = false) String dir,
                                   @RequestParam(required = false, defaultValue = "true") boolean rename) {
        String fileName = file.getOriginalFilename();
        String contentType = file.getContentType();
        if (rename) {
            fileName = IdUtil.simpleUUID() + StrUtil.DOT + FileUtil.extName(file.getOriginalFilename());
        }
        String fullName = BucketConstants.BUCKET + StrUtil.SLASH + fileName;
        String uploadPath = fileName;
        if (StrUtil.isNotBlank(dir)) {
            uploadPath = dir + StrUtil.SLASH + fileName;
            fullName = BucketConstants.BUCKET + StrUtil.SLASH + uploadPath;
        }
        FileStatVo stat = new FileStatVo();
        stat.setBucketName(BucketConstants.BUCKET);
        stat.setFileName(fileName);
        stat.setFullName(fullName);

        try {
//            minioTemplate.putObject(BucketConstants.BUCKET, uploadPath, file.getInputStream());
            minioTemplate.putObject(BucketConstants.BUCKET, uploadPath, file.getInputStream(),contentType);
        } catch (Exception e) {
            log.error("上传失败:{}", e.getMessage(), e);
            return Resp.failed("上传失败:" + e.getLocalizedMessage());
        }
        return Resp.ok(stat);
    }
/**
     * 上传文件
     *
     * @param bucketName bucket名称
     * @param objectName 文件名称
     * @param stream     文件流
     * @throws Exception https://docs.minio.io/cn/java-client-api-reference.html#putObject
     */
    public void putObject(String bucketName, String objectName, InputStream stream, String conType) throws Exception {
//        this.putObject(bucketName, objectName, stream, stream.available(), "application/octet-stream");
        this.putObject(bucketName, objectName, stream, stream.available(), conType);
    }

下载

/**
     * 下载文件
     *
     * @param file 文件路径
     */
    @GetMapping("/download")
    public void download(@RequestParam String file, HttpServletResponse response) {
        String bucket = org.apache.commons.lang3.StringUtils.substringBefore(file, StrUtil.SLASH);
        String filePath = org.apache.commons.lang3.StringUtils.substringAfter(file, StrUtil.SLASH);
        String fileName = org.apache.commons.lang3.StringUtils.substringAfterLast(file, StrUtil.SLASH);
        try (InputStream inputStream = minioTemplate.getObject(bucket, filePath)) {
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setCharacterEncoding("UTF-8");
            IoUtil.copy(inputStream, response.getOutputStream());
        } catch (Exception e) {
            log.error("读取异常:{}", file, e);
        }
    }

预览

/**
     * 在线预览文件
     *
     * @param file 文件路径
     */
    @GetMapping("/view")
    public void file(@RequestParam String file, HttpServletResponse response) {
        String bucket = StringUtils.substringBefore(file, StrUtil.SLASH);
        String filePath = StringUtils.substringAfter(file, StrUtil.SLASH);
        String fileName = org.apache.commons.lang3.StringUtils.substringAfterLast(file, StrUtil.SLASH);
        try (InputStream inputStream = minioTemplate.getObject(bucket, filePath)) {
            ObjectStat stat = minioTemplate.getObjectInfo(bucket, filePath);
            response.setContentType(stat.contentType());
//            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition", "inline; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            IoUtil.copy(inputStream, response.getOutputStream());
        } catch (Exception e) {
            log.error("读取异常:{}", file, e);
        }
    }

预览页面–easyui

view: function (filePath) {
            console.log("showfilepath:"+filePath);
            if(filePath.indexOf(".jpg") >= 0 || filePath.indexOf(".JPG") >= 0 || filePath.indexOf(".GIF") >= 0 || filePath.indexOf(".gif") >= 0 || filePath.indexOf(".png") >= 0 || filePath.indexOf(".PNG") >= 0){
                $('<img>', {
                    src: ctx + "/api/fs/view?file=" + filePath
                }).viewer('show');
                console.log("img:"+ctx + "/api/fs/view?file=" + filePath);
            } else {
                var url = ctx + "/api/fs/view?file=" + filePath;
                console.log("pdf:"+url);
                window.open(url,'_blank');//打开另一个窗口
                // let mywin = window.open('','_self');//本页打开
                // mywin.location.href = url;
            }
        },
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Ant Design的上传组件支持上传PDF文件并且预览PDF文件需要将PDF文件转换为图片格式,然后使用图片预览组件进行预览。以下是示例代码: ```jsx import React, { useState } from 'react'; import { Upload, Button, message, Spin } from 'antd'; import { LoadingOutlined, PlusOutlined } from '@ant-design/icons'; import { pdfjs, Document, Page } from 'react-pdf'; pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`; const UploadPDF = () => { const [fileList, setFileList] = useState([]); const [previewUrl, setPreviewUrl] = useState(''); const [loading, setLoading] = useState(false); const handleChange = ({ fileList }) => { setFileList(fileList); if (fileList.length > 0) { setLoading(true); const reader = new FileReader(); reader.readAsDataURL(fileList[0].originFileObj); reader.onloadend = () => { setPreviewUrl(reader.result); setLoading(false); }; } else { setPreviewUrl(''); } }; const handlePreview = () => { window.open(previewUrl); }; const handleRemove = () => { setFileList([]); setPreviewUrl(''); }; const uploadButton = ( <div> {loading ? <LoadingOutlined /> : <PlusOutlined />} <div style={{ marginTop: 8 }}>Upload</div> </div> ); return ( <div> <Upload fileList={fileList} onChange={handleChange} onRemove={handleRemove} beforeUpload={(file) => { if (file.type !== 'application/pdf') { message.error(`${file.name} is not a PDF file`); return false; } return true; }} showUploadList={false} > {fileList.length === 0 ? ( uploadButton ) : ( <Button onClick={handlePreview}>Preview</Button> )} </Upload> {previewUrl && ( <div style={{ marginTop: 16 }}> <Spin spinning={loading}> <Document file={previewUrl} onLoadSuccess={null}> <Page pageNumber={1} width={400} /> </Document> </Spin> </div> )} </div> ); }; export default UploadPDF; ``` 在这个示例中,我们使用了`react-pdf`库来渲染PDF文件的预览图。`handleChange`函数在上传PDF文件后将PDF文件转换为DataURL,然后设置预览图的URL。`handlePreview`函数用于打开预览图。`handleRemove`函数用于删除上传的PDF文件和预览图。在上传组件中,`beforeUpload`函数用于验证上传的文件是否为PDF文件。最后,`Document`和`Page`组件用于渲染PDF文件的预览图。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值