1

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

@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,我需要坚持使用字节数组。任何帮助表示赞赏。

4

1 回答 1

0

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

你有几个选择:

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

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

HttpEntity entity = new ByteArrayEntity(array);
httpPost.setEntity(entity);
于 2019-12-23T11:04:23.293 回答