The following functions will be implemented this time. ・ Create an API to upload photos -Receive data in binary without using MultipartFile -Output the file to the specified directory via Java -File names are automatically numbered by year, month, day, hour, minute, and second (the name of the upload source is not used) -Obtain binary information and get the compression format (extension) of the image For this part, I referred to the following information. → Determine the type of image from binary data
Controller
java:com.example.UsersController.java
@RequestMapping(path = "/users/upload", method = RequestMethod.POST)
public void upload(InputStream req) throws IOException {
ByteArrayOutputStream byteos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int size = 0;
while ((size = req.read(buf, 0, buf.length)) != -1) {
byteos.write(buf, 0, size);
}
String filename = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS").format(LocalDateTime.now());
Path uploadfile = Paths.get("Users/demo-kusa/image" + filename
+ "." + getFormat(byteos.toByteArray()));
try (OutputStream os = Files.newOutputStream(uploadfile, StandardOpenOption.CREATE)) {
os.write(byteos.toByteArray());
} catch (IOException ex) {
System.err.println(ex);
}
}
** See the linked article for ImageTypeCheck.java ** (I've made some modifications, but it worked as it is) ImageType.java
When sending binary data, there are several methods such as http client commands such as curl, javascript, and REST client, but this time I used Postman.
After writing so far, I noticed that IOException is tried and throws in Controller. I will refactor it at a later date. Although it has a purpose, it wastes resources by going through ByteArrayOutputStream, so review it. .. github kaikusakari/spring_crud
Recommended Posts