文章来源:https://www.toymoban.com/news/detail-810529.html
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://www.toymoban.com/news/detail-810529.html
到了这里,关于IO流读取上传文件的内容的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!