在spring mvc会将对象种的字节数组成员转换成base64编码的字符传格式,前台接收到数据后要进行base64界面才能恢复成原字节数组,网上有很多解决方案通过都修改produces = {"text/plain", "application/json"}为多媒体格式来解决;
public class ResponseByteArray { private String fileName; private byte[] file; public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public byte[] getFile() { return file; } public void setFile(byte[] file) { this.file = file; } } @RequestMapping(value = "/getDataByte", method = RequestMethod.GET) public ResponseEntity> uploadUImageGet() throws IOException { ResponseByteArray response = new ResponseByteArray(); File fileImage = new File("D://images//download1.jpg"); byte[] fileContent = Files.readAllBytes(fileImage.toPath()); response.setFileName("testFile.jpg"); response.setFile(fileContent); return new ResponseEntity(response, HttpStatus.OK); } }
{ "fileName": "testFile.jpg", "file":"/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxIQEg8PEhIPFRIPDw8QEA8QDw8PEBAPFREWFhUVFRUYHSggGBolHRUVITEhJSkrLi4uFx8zODMsNygtLisBCgoKDg0NFQ8PFSsdFR0tLS0tKysrKy0tKy0tNy03LS0rKy0tLSsrKzc3LS0rLSsrKy0rKzctLTcrLSstNy0tK//AABEIAQMAwgMBIgACEQEDEQH/xAAbAAABBQEBAAAAAAAAAAAAAAADAAECBAUGB//EAD8QAAIBAgMFBQUGBQIHAQAAAAECAAMRBCExBRJBUWEGMnGBkRMiUqHRFGJyscHwQpKisuEjkxUXM3OC0vEH/8QAGQEBAQEBAQEAAAAAAAAAAAAAAAECAwUE/8QAIBEBAQEAAwADAAMBAAAAAAAAABEBAgMSITFBEyJRB ... }
但是如果想将上边的json数据返回值变成如下格式该怎么办呢?
{ "fileName": "testFile.jpg", "file":[23,4,5,6,3,,7,45,6,5,34....] }
其实对原方法稍作修改即可,这里用到了gson,可以在方法种显示的将对象转换为json字符串,不用spring MVC默认的转换方式即可。
@RequestMapping(value = "/getDataByte", method = RequestMethod.GET) public String uploadUImageGet() throws IOException { 。。。 return new Gson().toJson(responseDto); }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)