?文章來源:http://www.zghlxwxcb.cn/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("關(guān)閉流失敗!", e);
}
}
return outputStream != null ? outputStream.toString() : null;
}
}
文章來源地址http://www.zghlxwxcb.cn/news/detail-810529.html
到了這里,關(guān)于IO流讀取上傳文件的內(nèi)容的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!