代码
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
/**
* @author: Curiosity
* @Date: 2020/11/1 15:44
* @Description: SpringMvc返回文件的几种方式
*/
@RestController
public class ImageController {
private static final String PATH = "D:\\360MoveData\\Users\\Desktop\\QQ截图20190608195316.png";
/**
* 通过byte 数组获取图片
*
* @return
* @throws IOException
*/
@RequestMapping(value = "/image", produces = MediaType.IMAGE_JPEG_VALUE)
public byte[] getImageByByteArray() throws IOException {
File file = new File(PATH);
try (FileInputStream inputStream = new FileInputStream(file)) {
byte[] bytes = new byte[inputStream.available()];
inputStream.read(bytes, 0, inputStream.available());
return bytes;
}
}
/**
* 通过FileSystemResource返回图片
*
* @return
* @throws IOException
*/
@RequestMapping(value = "/image1", produces = MediaType.IMAGE_JPEG_VALUE)
public ResponseEntity<Resource> getImageByFileSystemResource() throws IOException {
File file = new File(PATH);
FileSystemResource fileSystemResource = new FileSystemResource(file);
return ResponseEntity.ok(fileSystemResource);
}
/**
* 通过ByteArrayResource返回图片
*
* @return
* @throws IOException
*/
@RequestMapping(value = "/image2", produces = MediaType.IMAGE_JPEG_VALUE)
public ResponseEntity<Resource> getImageByByteArrayResource() throws IOException {
File file = new File(PATH);
ByteArrayResource byteArrayResource = new ByteArrayResource(Files.readAllBytes(file.toPath()));
return ResponseEntity.ok(byteArrayResource);
}
}
扩展
可以通过
BufferedImage
做为返回值去返回图片,前提是需要加入BufferedImageHttpMessageConverter
转换器
@Bean
public BufferedImageHttpMessageConverter bufferedImageHttpMessageConverter(){
return new BufferedImageHttpMessageConverter();
}