?
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;
}
}