File相关的api: 上传文件, 下载文件, 解析压缩包,打压缩包

工具类

其中的包含swagger注解,使用时可以直接去掉,不影响功能

package com.hmy.azure.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

@Tag(name="File API", description = "与文件(包括压缩包)相关的api, 上传,下载")
@RestController
@RequestMapping("/api/file")
public class FileController {

    @Operation(summary = "Parse Zip",description = "上传压缩包并解压,获取文件内容")
    @PostMapping(value = "/zip/parse",headers = "content-type=multipart/form-data")
    public ResponseEntity<Object> parseZip(@RequestPart("file") MultipartFile multipartFile){
        List<Map<String,Object>> resultList = new ArrayList<>();
        ByteArrayOutputStream bo = null;
        try(InputStream in = multipartFile.getInputStream();//如果是byte[],则new ByteArrayInputStream(bytes)
            ZipInputStream zipInputStream = new ZipInputStream(in)) {
            ZipEntry zipEntry = null;
            while ((zipEntry=zipInputStream.getNextEntry())!=null){
                bo = new ByteArrayOutputStream();
                int n;
                byte[] outBytes = new byte[1024];
                while ((n= zipInputStream.read(outBytes))!=-1){
                    bo.write(outBytes,0,n);
                }

                String fileName = zipEntry.getName();
                String content = new String(bo.toByteArray());
                Map<String,Object> map = new HashMap<>();
                map.put("fileName",fileName);
                map.put("content",content);
                resultList.add(map);
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if(bo != null){
                try {
                    bo.close();
                }catch (IOException e){
                    throw new RuntimeException(e);
                }
            }
        }
        return ResponseEntity.ok(resultList);
    }

    @Operation(summary = "Download Zip",description = "将文件打成压缩包并下载")
    @GetMapping("/zip/download")
    public void downloadZip(HttpServletResponse response){
        String contentType = "application/zip";
        String disposition = "attachment; fileName="+ URLDecoder.decode("code.zip");
        setResponse(response,contentType,disposition);

        String path = "D:/temp";
        File fileDir = new File(path);
        File[] files = fileDir.listFiles();

        try(OutputStream os = response.getOutputStream();
            ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(os))) {
            //Set the zip method
            zos.setMethod(ZipOutputStream.DEFLATED);
            //Put files to zip
            for (File file:files) {
                //压缩文件
                ZipEntry zipEntry = new ZipEntry(file.getName());
                zos.putNextEntry(zipEntry);
                //获取文件内容
                InputStream inputStream = new FileInputStream(file);
                byte[] content = inputStream.readAllBytes();
                zos.write(content);
                zos.closeEntry();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Operation(summary = "Download file",description = "文件下载")
    @GetMapping("/download")
    public void downloadFile(HttpServletResponse response){
        String contentType = "application/x-msdownload";
        String disposition = "attachment; fileName="+ URLDecoder.decode("1.txt");
        setResponse(response,contentType,disposition);

        String path = "D:/temp/1.txt";
        File file = new File(path);
        try(OutputStream os = response.getOutputStream();
            InputStream inputStream = new FileInputStream(file);) {
            byte[] bytes = inputStream.readAllBytes();
            os.write(bytes);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Operation(summary = "Upload file",description = "文件上传")
    @PostMapping(value = "/upload",headers = "content-type=multipart/form-data")
    public ResponseEntity<Object> uploadFile(@RequestPart("file") MultipartFile multipartFile){
        String content = null;
        String path = "D:/temp/3.txt";
        File file = new File(path);
        try(OutputStream os = new FileOutputStream(path);
            InputStream inputStream = multipartFile.getInputStream()) {
            byte[] bytes = inputStream.readAllBytes();
            content = new String(bytes);
            os.write(bytes);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return ResponseEntity.ok(content);
    }

    private void setResponse(HttpServletResponse response,String contentType,String disposition){
        response.setContentType(contentType);
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION,disposition);
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值