Изображения, которые не сохраняются в директории ресурсов Spring Boot mvc приложения - PullRequest
0 голосов
/ 29 апреля 2020

Я пытаюсь сохранить файлы изображений в каталоге, который находится в папке ресурсов проекта, приведенный ниже код не выдает никакой ошибки и не сохраняет файл в указанном месте, я знаю, что сохранение файла в ресурсах - плохая идея, но просто попытка переместить файл позже в файл S3.

 @PostMapping("/add")
public String addBook(@ModelAttribute("book") Book book, HttpServletRequest request) throws IOException {
    bookService.save(book);
    MultipartFile bookImage = book.getBookImage();
    try {
        byte[] bytes = bookImage.getBytes();
        String bookName = book.getId() + ".png";
        BufferedOutputStream bf = new BufferedOutputStream(new FileOutputStream(new File(
                "src/main/resources/static/image/books/"+bookName
        )));
        bf.write(bytes);
        bf.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "redirect:bookList";
}

1 Ответ

0 голосов
/ 04 мая 2020

Исходя из ваших вопросов и комментариев, приведенных выше, особенно когда вы думаете о переходе от хранилища файловой системы к S3, вы можете взглянуть на проект сообщества под названием [Spring Content] [1]. Этот проект позволяет вам управлять контентом (то есть вашими сгенерированными изображениями книг) и связывать их с вашими объектами данных Spring. Он предоставляет ту же модель программирования, что и Spring Data, только для неструктурированного контента, такого как файлы, изображения, видео и т. Д. c.

Например, если вы используете Spring Data, вы можете добавить это в свои проекты следующим образом. ,

pom. xml (для Spring Web MVC. Также доступны стартеры весенней загрузки)

   <!-- Spring dependencies -->
   ...

   <!-- Java API -->
   <dependency>
      <groupId>com.github.paulcwarren</groupId>
      <artifactId>spring-content-fs</artifactId>
      <version>1.0.0.M11</version>
   </dependency>

   <!-- REST API -->
   <dependency>
      <groupId>com.github.paulcwarren</groupId>
      <artifactId>spring-content-rest</artifactId>
      <version>1.0.0.M11</version>
   </dependency>

StoreConfig. java

@Configuration
@EnableFilesystemStores
@Import(RestConfiguration.class)
public class EnableFilesystemStoresConfig {

    @Bean
    File filesystemRoot() throws IOException {
        return new File("/path/to/your/book/images");
    }

    @Bean
    FileSystemResourceLoader fileSystemResourceLoader() {
        return new FileSystemResourceLoader(filesystemRoot().getAbsolutePath());
    }

}

BookImageStore. java

@StoreRestResource(path="bookImages")
public interface BookImageStore extends ContentStore<Book, String> {
}

And to add Spring Content-annotated fields to your Spring Data entities, like this:

Книга. java

@Entity
public class Book {
   @Id
   @GeneratedValue
   private long id;

   ...other existing fields...

   @ContentId
   private String contentId;

   @ContentLength
   private long contentLength = 0L;

   @MimeType
   private String mimeType;

   ...
}

This is all you need.  When your application starts it will see the `spring-content-fs` dependency on your classpath and the BookImageStore interface and it will inject a file-based implementation.  Moreover, it will see the spring-content-rest dependency and inject an @Controller implementation providing a REST API for handling your book images that will forward REST calls onto the BookStoreImage so you dont have to worry about implementing any of this yourself.

So:

`POST /bookImages/{bookId} -F "image=@/some/path/to/an/image.jpg"` 

will upload `image.jpg` to `/path/to/your/uploaded/images/` and update the fields on the Book entity so the content is associated.

`GET /bookImages/{bookId}` -H 'Accept: image/jpeg' 

will fetch it again.

A couple of additional notes;
- I would strongly recommend that you use a path outside of src/resources so that have more flexibility with how you deploy your war/jar
- if later on you want to change the backend storage from the filesystem to s3 all you would have to do it switch out the `spring-content-fs` dependency for `spring-content-s3` and update the StoreConfig to provide an S3 client bean instead of a FilesystemResourceLoader bean.

HTH

  [1]: https://paulcwarren.github.io/spring-content/
  [2]: https://github.com/paulcwarren/spring-content-examples

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...