Войти Регистрация
Код-ревью

41. Загрузка фото в чат покупателя и продавца на Авито

Средняя

Java · 34 строк

Покупатель и продавец обмениваются в чате фото товара и PDF: чеки, гарантийные талоны. Лимит — 10 МБ на файл. Файлы раздаются с того же домена по адресу /files/....

В приложении spring.servlet.multipart.max-file-size = 200MB: тот же лимит нужен соседнему контроллеру видео. Чатов 40 млн, в каждом двое участников. Отметьте строки с ошибками.

В работе: Скрепка в чате объявления: фото дефекта, скриншот перевода, чек.

Как проверяем Нажмите на строку с ошибкой и коротко напишите, что не так. Баг засчитан, если отмечена хотя бы одна его строка. Зачёт — найдено не меньше 60 % багов с учётом серьёзности (критичный весит 3, обычный 2, мелкий 1), а лишних отметок не больше, чем багов в коде. Пустые строки, скобки и комментарии лишними не считаем. Ответ один на подход: после него показываем разбор.
Springзагрузка файловpath traversalXSSдоступресурсы

Источник: наша задача на данных Авито: мессенджер между покупателем и продавцом. Условие пересказано своими словами.

  1. @RestController
  2. @RequestMapping("/api/messenger")
  3. public class AttachmentController {
  4. private static final long MAX_SIZE = 10 * 1024 * 1024;
  5. private static final Path STORAGE = Paths.get("/data/attachments");
  6. private final ChatRepository chats;
  7. private final AttachmentRepository attachments;
  8. public AttachmentController(ChatRepository chats, AttachmentRepository attachments) {
  9. this.chats = chats;
  10. this.attachments = attachments;
  11. }
  12. @PostMapping("/chats/{chatId}/attachments")
  13. public AttachmentDto upload(@PathVariable long chatId, @RequestParam("file") MultipartFile file,
  14. @AuthenticationPrincipal UserPrincipal user) throws IOException {
  15. Chat chat = chats.findById(chatId).orElseThrow(NotFoundException::new);
  16. byte[] bytes = file.getBytes();
  17. if (bytes.length > MAX_SIZE) {
  18. throw new PayloadTooLargeException();
  19. }
  20. String contentType = file.getContentType();
  21. if (!contentType.startsWith("image/") && !contentType.equals("application/pdf")) {
  22. throw new UnsupportedMediaTypeException();
  23. }
  24. Path target = STORAGE.resolve(chatId + "/" + file.getOriginalFilename());
  25. Files.createDirectories(target.getParent());
  26. OutputStream out = new FileOutputStream(target.toFile());
  27. out.write(bytes);
  28. Attachment a = attachments.save(new Attachment(chatId, user.getId(), target.toString(), contentType));
  29. return new AttachmentDto(a.getId(), "/files/" + chatId + "/" + file.getOriginalFilename());
  30. }
  31. }