Spring Server自动删除存储在应用程序文件夹中的文件

阿尔贝托·克雷斯波

我有一个充当启动应用程序的Spring Server。

我使用h2驱动程序通过JPA保存不同的对象。所有这些对象正在更新OK。

我使用此类来管理将在服务器上更新的所有文件:

public class LocalFileManager {
/**
 * This static factory method creates and returns a 
 * ImageFileManager object to the caller. Feel free to customize
 * this method to take parameters, etc. if you want.
 * 
 * @return
 * @throws IOException
 */
public static LocalFileManager get() throws IOException {
    return new LocalFileManager();
}
private Path targetDir_ = Paths.get("locals");
// The ImageFileManager.get() method should be used
// to obtain an instance
private LocalFileManager() throws IOException{
    if(!Files.exists(targetDir_)){
        Files.createDirectories(targetDir_);
    }
}
// Private helper method for resolving Image file paths
private Path getLocalPath(Postosaude g, int PictureNumberByLocal){
    assert(g != null);
    return targetDir_.resolve("picture"+"-"+g.getId()+"-"+PictureNumberByLocal+".jpg");
}
/**
 * This method returns true if the specified Image has binary
 * data stored on the file system.
 * 
 * @param v
 * @return
 */
public boolean hasLocalData(Postosaude g,int i){
    Path source = getLocalPath(g, i);
    return Files.exists(source);
}
/**
 * This method copies the binary data for the given Image to
 * the provided output stream. The caller is responsible for
 * ensuring that the specified Image has binary data associated
 * with it. If not, this method will throw a FileNotFoundException.
 * 
 * @param v 
 * @param out
 * @throws IOException 
 */
public void copyGiftData(Postosaude g,int i, OutputStream out) throws IOException {
    Path source = getLocalPath(g,i);
    if(!Files.exists(source)){
        throw new FileNotFoundException("Unable to find the referenced gift file for giftId:"+g.getId());
    }
    Files.copy(source, out);
}
/**
 * This method reads all of the data in the provided InputStream and stores
 * it on the file system. The data is associated with the Image object that
 * is provided by the caller.
 * 
 * @param v
 * @param ImageData
 * @throws IOException
 */
public void saveLocalData(Postosaude g,int i, InputStream localData) throws IOException{
    assert(localData != null);
    Path target = getLocalPath(g,i);
    Files.copy(localData, target, StandardCopyOption.REPLACE_EXISTING);
}
public void deleteImageFromLocal(Postosaude g, int i) throws IOException
{
    Path target = getLocalPath(g,i);
    Files.delete(target);
}

}

该代码运行良好。它将所有我更新的文件(图像)正确保存在Folder中/locals/,但是如果重新启动Server,它们将被自动删除

这是来自Application类的代码,也许可以帮助您找出错误:

@EntityScan(basePackages= "palmaslab.mapas.repository")
@EnableJpaRepositories(basePackages= "palmaslab.mapas.repository"/*.PostoSaudeRepository.class*/)
@Configuration
@EnableAutoConfiguration
@ComponentScan(basePackages="palmaslab.mapas.controller")
@Import({palmaslab.mapas.security.SecurityConfiguration.class})
@EnableWebMvc
@PropertySource("application.properties")
public class Application extends WebMvcConfigurerAdapter{
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
    "classpath:/META-INF/resources/", "classpath:/resources/",
    "classpath:/static/", "classpath:/public/" };
public static void main(String[] args) {
      SpringApplication.run(Application.class, args);
     }
 @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(
            DataSource dataSource, JpaVendorAdapter jpaVendorAdapter) {
        LocalContainerEntityManagerFactoryBean lef = new LocalContainerEntityManagerFactoryBean();
        lef.setDataSource(dataSource);
        lef.setJpaVendorAdapter(jpaVendorAdapter);
        lef.setPackagesToScan("palmaslab.mapas.controller");
        return lef;
    }
    @Bean
    public JpaVendorAdapter jpaVendorAdapter() {
        HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
        hibernateJpaVendorAdapter.setShowSql(true);
        hibernateJpaVendorAdapter.setGenerateDdl(true); //Auto creating scheme when true
        hibernateJpaVendorAdapter.setDatabase(Database.H2);//Database type
        return hibernateJpaVendorAdapter;
    }
    @Bean 
    public SpringTemplateEngine templateEngine() { 
        SpringTemplateEngine engine = new SpringTemplateEngine();
        Set<IDialect> dialects = new HashSet<IDialect>();
        dialects.add(new SpringSecurityDialect());
        dialects.add(new LayoutDialect());
        engine.setAdditionalDialects(dialects);
        LinkedHashSet<ITemplateResolver> templateResolvers = new LinkedHashSet<ITemplateResolver>(2);
        templateResolvers.add(templateResolverServlet());
        templateResolvers.add(layoutTemplateResolverServlet());
        engine.setTemplateResolvers(templateResolvers);
        return engine;
    } 
   @Bean 
    public ServletContextTemplateResolver layoutTemplateResolverServlet() { 
        ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
        templateResolver.setPrefix("/WEB-INF/layout/");
        templateResolver.setSuffix("");
        templateResolver.setTemplateMode("LEGACYHTML5");
        templateResolver.setOrder(1);
        templateResolver.setCacheable(false);
        return templateResolver;
    } 
     @Bean 
    public ServletContextTemplateResolver templateResolverServlet() { 
        ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
        templateResolver.setPrefix("/WEB-INF/view/");
        templateResolver.setSuffix(".html");
        templateResolver.setTemplateMode("LEGACYHTML5");
        templateResolver.setOrder(2);
        templateResolver.setCacheable(false);
        return templateResolver;
    } 
   @Bean 
     public ViewResolver thymeleafViewResolver() { 
        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
        resolver.setTemplateEngine(templateEngine());
        resolver.setOrder(1);
        resolver.setCharacterEncoding("ISO-8859-1");
        resolver.setCache(false);
        return resolver;
    }     
@Bean
public ServletRegistrationBean dispatcherRegistration() {
    ServletRegistrationBean registration = new ServletRegistrationBean(dispatcherServlet());
    registration.addUrlMappings("/");
    registration.setLoadOnStartup(1);
    return registration;
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
    configurer.enable();
}
@Bean
public DispatcherServlet dispatcherServlet() {
    return new DispatcherServlet();
}
@Bean
public MultipartConfigElement multipartConfigElement() {
    MultipartConfigFactory factory = new MultipartConfigFactory();
    factory.setMaxFileSize("999999KB");
    factory.setMaxRequestSize("999999KB");
    return factory.createMultipartConfig();
}
 @Bean
  public MultipartResolver multipartResolver() {
    CommonsMultipartResolver resolver = new CommonsMultipartResolver();
    resolver.setMaxUploadSize(1000000000);
    return resolver;
  }
@Bean
public CommonsMultipartResolver filterMultipartResolver() {
    CommonsMultipartResolver resolver=new CommonsMultipartResolver();
    resolver.setDefaultEncoding("ISO-8859-1");
    resolver.setMaxUploadSize(500000000);
    resolver.setMaxInMemorySize(500000000);
    return resolver;
}
@Bean
public EmbeddedServletContainerFactory servletContainer() {
    TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory();
    factory.setPort(8080);
    factory.setSessionTimeout(1, TimeUnit.MINUTES);
    //factory.addErrorPages(new ErrorPage(HttpStatus.404, "/notfound.html"));
    return factory;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    if (!registry.hasMappingForPattern("/webjars/**")) {
        registry.addResourceHandler("/webjars/**").addResourceLocations(
                "classpath:/META-INF/resources/webjars/");
    }
    if (!registry.hasMappingForPattern("/locals/**")) {
        registry.addResourceHandler("/locals/**").addResourceLocations(
                 "classpath:/locals");
      }
}

有人可以找到我的错误吗?

谢谢,

Bohuslav Burghardt

如果您在部署应用程序的位置创建或修改文件,则在重新启动服务器时这些文件将被删除,因为将重新部署该应用程序。

如果您希望文件在重新部署后仍然有效,则您的存储基础目录必须位于应用程序文件夹(例如/srv/myapp/locals)之外。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在Spring Boot应用程序中未创建WEB-INF文件夹吗?

未在 Spring Boot 应用程序的 WEB-INF 目录中创建“资源”文件夹

打开应用程序文件夹中的文件

创建文件并将其存储在Java Web应用程序文件夹中

Laravel删除应用程序文件夹(根)中的文件

如何在传统的tomcat webapps文件夹中部署Spring Boot MVC应用程序?

用于多租户应用程序或多个要观看的文件夹的 Spring IntegrationFlow

如何使用 IDE 和 Java -jar 命令读取 Spring Boot 应用程序中资源文件夹中存在的文件?

如果 Spring 启动应用程序文件中没有属性,则 Sprint 启动 2.0.5 @ConfigurationProperties 不会填充列表

如何设置Spring应用程序的日志文件名并登录到tomcat / logs文件夹?

如何从应用程序视图中删除空的应用程序文件夹

应用扩展程序如何访问包含应用程序文档/文件夹中的文件

在 spring-boot 应用程序中,如何将静态内容(例如图像)从本地文件夹而不是资源文件夹加载到 jsp 中?

如何在GNOME应用程序菜单中创建应用程序文件夹?

Cordova自动更新应用程序文件夹

Laravel显示来自存储/应用程序文件夹的图像路径

ASP C#中来自fileUpload的应用程序文件夹中的SaveAs()文件

通过Spring Boot应用程序将日志文件存储在AWS S3中

React Redux应用程序文件夹结构

Android Studio创建应用程序文件夹

启动应用程序文件夹位置

邮编Web应用程序文件夹

斯威夫特:如何确定应用程序文件夹?

Ubuntu 20.04 应用程序文件夹

如何将上载的文件存储到MVC应用程序中应用程序文件夹以外的位置

手动删除应用程序文件夹以卸载软件包

cordova 应用程序文件夹中没有 .xcodeproj 文件

无法访问Grails 3中的Web应用程序文件夹文件

Applescript 重命名应用程序文件夹中的文件