IO流读取上传文件的内容

发布时间:2024年01月13日

?

package com.dj.springtest.controller;

import com.alibaba.fastjson.JSON;
import com.dj.springtest.model.dto.UploadDTO;
import com.dj.springtest.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * User: ldj
 * Date: 2024/1/10
 * Time: 22:10
 * Description: No Description
 */
@RestController
public class FileController {

    @Autowired
    private FileService fileService;
    
    @PostMapping("/test/read/file")
    public String readFile(@RequestPart("file") MultipartFile file) throws IOException {
        return fileService.readFile(file);
    }

}
package com.dj.springtest.service.impl;

import com.dj.springtest.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;

/**
 * User: ldj
 * Date: 2024/1/13
 * Time: 19:02
 * Description: No Description
 */
@Slf4j
@Service
public class FileServiceImpl implements FileService {

    @Override
    public String readFile(MultipartFile file) {
        if (Objects.isNull(file)) {
            return null;
        }

        InputStream inputStream = null;
        ByteArrayOutputStream outputStream = null;
        try {
            String originalFilename = file.getOriginalFilename();
            log.info("文件名:{}", originalFilename);
            inputStream = file.getInputStream();
            outputStream = new ByteArrayOutputStream();

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
            }
        } catch (IOException e) {
            log.error("读取文件失败!", e);
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.flush();
                    outputStream.close();
                }

                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                log.error("关闭流失败!", e);
            }
        }
        return outputStream != null ? outputStream.toString() : null;
    }

}

文章来源:https://blog.csdn.net/dj1955/article/details/135574705
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。