上传下载 java

package springboot_001.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springboot_001.config.R;
import springboot_001.dao.Dao;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/ows/test")
public class FileController {

    private static String SAVE_FILE_DIR = "./files";

    @Autowired
    Dao dao;

    @PostMapping("/upload")
    public @ResponseBody
    Map<String, Object> uploadFile(
            @RequestParam("file") MultipartFile file, @RequestParam("instanceId") String instanceId,
            @RequestParam("fieldName") String fieldName) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        File dir = new File(SAVE_FILE_DIR + "/" + sdf.format(new Date()));

        if (!dir.exists()) {
            dir.mkdirs();
        }

        String name = file.getOriginalFilename();
        String extName = "";

        if (name.contains(".")) {
            extName = name.substring(name.lastIndexOf(".") + 1, name.length());
        }
        String saveFileName = UUID.randomUUID().toString() + "." + extName;
        String savePath = dir.getPath() + File.separator + saveFileName;
        String saveLocalPath = dir.getCanonicalPath() + File.separator + saveFileName;
        file.transferTo(new File(saveLocalPath));
        Map<String, Object> fileObj = new HashMap<>();
        fileObj.put("NAME", name);
        fileObj.put("EXT_NAME", extName);
        fileObj.put("SAVE_PATH", savePath);
        fileObj.put("FILE_SIZE", file.getSize());
        fileObj.put("INSTANCE_ID", instanceId);
        fileObj.put("FIELD_NAME", fieldName);
        dao.saveOrUpdate(R.FILE, fileObj);
        return fileObj;
    }

    @GetMapping("/download/{fileId}")
    public void download(@PathVariable("fileId") String fileId,
                         HttpServletResponse response) throws Exception {
        Map<String, Object> fileObj = dao.findById2Map(R.FILE, fileId, null);
        String fileName = (String) fileObj.get("NAME");
        String savePath = (String) fileObj.get("SAVE_PATH");
        String extName = (String) fileObj.get("EXT_NAME");
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(savePath))) {
            fileName = URLEncoder.encode(fileName, "UTF-8");// IE浏览器
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
            if ("xls".equals(extName) ||
                    "xlsx".equals(extName)) {
                response.setContentType("application/vnd.ms-excel;charset=utf-8");
            } else if ("doc".equals(extName) ||
                    "docx".equals(extName)) {
                response.setContentType("application/msword;charset=utf-8");
            } else if ("ppt".equals(extName) ||
                    "pptx".equals(extName)) {
                response.setContentType("application/vnd.ms-powerpoint;charset=utf-8");
            } else if ("pdf".equals(extName)) {
                response.setContentType("application/pdf;charset=utf-8");
            } else if ("jpg".equals(extName) ||
                    "jpeg".equals(extName)) {
                response.setContentType("image/jpeg;charset=utf-8");
            } else if ("png".equals(extName)) {
                response.setContentType("image/png;charset=utf-8");
            } else if ("gif".equals(extName)) {
                response.setContentType("image/gif;charset=utf-8");
            } else {
                response.setContentType("application/octet-stream;charset=utf-8");
            }
            try (BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())) {
                byte[] buffered = new byte[1024];
                int len;
                while ((len = bis.read(buffered)) != -1) {
                    bos.write(buffered, 0, len);
                }
            }
        }
    }
}

 

MinIO 是一个开源的对象存储服务器,常用于云原生应用中。要在 Java 中实现 MinIO 的上传下载功能,你可以使用官方提供的 MinIO SDK。以下是简单的步骤: 1. **添加依赖**: 首先,你需要通过 Maven 或 Gradle 添加 MinIO SDK 到你的项目中。对于 Maven,添加到 `pom.xml` 文件: ```xml <dependency> <groupId>io.minio</groupId> <artifactId>minio</artifactId> <version>latest版本号</version> </dependency> ``` 更新`latest版本号`为实际的 MinIO SDK 版本。 2. **初始化连接**: 创建一个 `MinioClient` 实例,需要提供 endpoint (存储服务器地址) 和 access key (访问密钥): ```java Minio minioClient = new Minio("http://your-minio-endpoint.com", "ACCESS_KEY", "SECRET_KEY"); ``` 3. **上传文件**: 要上传文件,可以使用 `putObject()` 方法: ```java String bucketName = "your-bucket-name"; String objectName = "path/to/local/file.txt"; File file = new File(objectName); minioClient.putObject(bucketName, objectName, file); ``` 4. **下载文件**: 下载文件同样使用 `getObject()` 方法: ```java Response response = minioClient.getObject(new GetObjectRequest(bucketName, objectName)); InputStream inputStream = response.data(); // 将流保存到本地文件或其他目的地 File outputFile = new File("path/to/downloaded/file.txt"); Files.copy(inputStream, outputFile.toPath()); ``` 5. **错误处理**: 始终记得捕获异常并妥善处理网络错误、权限问题等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值