Spring 框架:接收到的字节数组已损坏

Spring Framework: Byte Array is corrupted when received

我想创建一个使用 Spring 框架处理字节数组的文件上传系统。我有一个控制器如下:

@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();
        }

    }
}

和这样的服务:

@Service
public class FileUploadService {

    @Value("${app.upload.dir:${user.home}}")
    public String uploadDir;

    public HashMap<String, String> saveFile(byte[] file, String fileName, String fileType) throws Exception {

        try {
            Path copyLocation = Paths
                    .get(uploadDir + File.separator + StringUtils.cleanPath(fileName));
            String pathString = copyLocation.toString();
            FileOutputStream stream = new FileOutputStream(pathString);
            stream.write(file);
            String fileSize = String.valueOf(Files.size(copyLocation));
            HashMap<String, String> result = new HashMap<String, String>();
            result.put("filePath", pathString);
            result.put("fileSize", fileSize);

            return result;

        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("Could not store file " + fileName
                    + ". Please try again!");
        }

    }

}

我正在使用使用 Apache HttpClient 的代码测试此 API:

public class app {

        public static void main(String[] args) throws IOException, InterruptedException {

            byte[] array = Files.readAllBytes(Paths.get("/Users/hemodd/Desktop/test-pic.png"));

            CloseableHttpClient client = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost("http://localhost:8080");

            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addTextBody("fileName", "Newwwww");
            builder.addTextBody("fileType", "png");
            builder.addBinaryBody("file", array);

            HttpEntity multipart = builder.build();
            httpPost.setEntity(multipart);

            CloseableHttpResponse response = client.execute(httpPost);
            client.close();
        }
    }

现在,问题是写入接收到的字节数组的结果是一个损坏的文件。我不想使用 MultipartFile,我需要坚持使用字节数组。 感谢任何帮助。

问题在于在您的控制器中传递文件: @RequestParam("file") byte[] file

您有多种选择:

  • 使用分段文件上传: @RequestParam("file") MultipartFile file
  • 从请求正文中解析字节数组: @RequestBody byte[] file
  • 将数据编码为字符串。在您的示例中,如果您想将字节作为参数发送,则必须对二进制数据进行编码,以便它可以作为字符串发送(例如,使用 Base64)。然后在服务器端解码。

您的测试应用创建并发送多部分请求。要在正文中发送字节数组,您必须将其更改为:

HttpEntity entity = new ByteArrayEntity(array);
httpPost.setEntity(entity);