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