Java Spring框架:收到时字节数组已损坏
我想创建一个文件上传系统,使用Spring框架与字节数组一起工作。我有一个控制器,如下所示:Java Spring框架:收到时字节数组已损坏,java,arrays,spring,rest,spring-framework-beans,Java,Arrays,Spring,Rest,Spring Framework Beans,我想创建一个文件上传系统,使用Spring框架与字节数组一起工作。我有一个控制器,如下所示: @Controller public class FileUploadController { @Autowired FileUploadService fileService; @GetMapping("/") public void index() { System.out.println("Show Upload Page"); }
@Controller
public class FileUploadController {
@Autowired
FileUploadService fileService;
@GetMapping("/")
public void index() {
System.out.println("Show Upload Page");
}
@PostMapping("/")
public void uploadFile(@RequestParam("file") byte[] file, @RequestParam("fileName")String fileName, @RequestParam("fileType") String fileType, RedirectAttributes redirectAttributes) {
try {
HashMap<String, String> result = fileService.saveFile(file,fileName,fileType);
String filePath = result.get("filePath");
String fileSize = result.get("fileSize");
System.out.println("Path " + filePath + " " + fileSize + " Bytes");
} catch (Exception e) {
e.printStackTrace();
}
}
}
现在,问题是写入接收到的字节数组的结果是一个损坏的文件。我不想使用MultipartFile,我需要坚持使用字节数组。
非常感谢您的帮助。问题在于在控制器中传递文件:
@RequestParam(“文件”)字节[]文件
您有几个选择:
- 使用多部分文件上载:
@RequestParam(“文件”)多部分文件
- 从请求正文分析字节数组:
@RequestBody byte[]文件
- 将数据编码为字符串。在您的示例中,如果要发送字节作为参数,则必须对二进制数据进行编码,以便将其作为字符串发送(例如,使用)。然后在服务器端解码
您的测试应用程序创建并发送多部分请求。要在正文中发送字节数组,必须将其更改为:
HttpEntity entity = new ByteArrayEntity(array);
httpPost.setEntity(entity);
在控制器中传递文件时出现问题:
@RequestParam(“文件”)字节[]文件
您有几个选择:
- 使用多部分文件上载:
@RequestParam(“文件”)多部分文件
- 从请求正文分析字节数组:
@RequestBody byte[]文件
- 将数据编码为字符串。在您的示例中,如果要发送字节作为参数,则必须对二进制数据进行编码,以便将其作为字符串发送(例如,使用)。然后在服务器端解码
您的测试应用程序创建并发送多部分请求。要在正文中发送字节数组,必须将其更改为:
HttpEntity entity = new ByteArrayEntity(array);
httpPost.setEntity(entity);
您能否在控制器中使用MultipartFile
而不是字节数组:@RequestParam(“file”)MultipartFile file
?是的,但我需要能够从客户端接收字节数组。在这种情况下,您必须使用@RequestBody byte[/code>。并将测试代码更改为HttpEntity entity=newbytearrayentity(数组);httpPost.setEntity(实体)代码>谢谢!现在可以了。你能解释一下为什么我的方法不起作用吗?你能在你的控制器中使用多部分文件
而不是字节数组吗:@RequestParam(“file”)多部分文件
?是的,但我需要能够从客户端接收字节数组。在这种情况下,你必须使用@RequestBody byte[]file
。并将测试代码更改为HttpEntity entity=newbytearrayentity(数组);httpPost.setEntity(实体)代码>谢谢!现在可以了。你能解释一下为什么我的方法不起作用吗?
HttpEntity entity = new ByteArrayEntity(array);
httpPost.setEntity(entity);