如何将JPG格式图像转为application/octet-stream文件流格式

由于发现前端接收的是application/octet-stream流数据,所以我想将后端的图像转为application/octet-stream流数据,通过搜索网上例子还没转化成功。有没有大佬有思路或者做过类似的?

很奇怪的需求,application/octet-stream 其实是在没法获取文件的媒体类型时使用的,通俗来说,它可以用在一切二进制文件上。

但是你这明明都明确是jpg格式文件了。为啥还要用application/octet-stream ?可以手动给文件设置一个ContentType。

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import javax.servlet.http.HttpServletResponse;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/demo")
public class DemoController {
	
	@GetMapping
	public void demo (HttpServletResponse response) throws IOException {
		
		Path file = Paths.get("C:\\logo.png");
		
		// 设置 ContentType 为 application/octet-stream
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        
        Files.copy(file, response.getOutputStream());
	}
}

但是浏览器直接请求 application/octet-stream ,浏览器会把整个响应当做一个文件下载。因为浏览器也不知道你这文件到底是啥类型文件。

好的,听你这么说,应该是我对application/octet-stream格式的用意不太了解了,谢谢!