【问题标题】:save user's images in a folder on file system Spring MVC将用户的图像保存在文件系统 Spring MVC 上的文件夹中
【发布时间】:2017-06-19 14:10:57
【问题描述】:

我有一个应用程序,用户可以在其中输入一些信息和图像,所以首先我将图像保存在数据库中,但我读到这不是一个好的做法,并且在部署应用程序时会产生成本。所以我想将图像保存在文件系统上,我读到我们不应该将它们保存在应用程序中,所以我想将它们保存在文件系统的外部文件夹中。我在文件夹 E:/images 中选择它们,效果很好。我的问题是我可以在生产应用程序中做什么来保存图像(不会有 E:/images),如何在部署应用程序的服务器上创建一个文件夹,以及如何在控制器中提及它而不是(E:/图像)。我正在使用 Spring MVC。 这是我的控制器:

@RequestMapping(value="/save",method=RequestMethod.POST)
    public String add ( @RequestParam("prix") Long prix, 
            RequestParam("adresse") String ville,
            @RequestParam("categorie") String categorie,
            @RequestParam("photos") MultipartFile file,
            ) throws FileNotFoundException


 {

   String chemin=null;
   if (!file.isEmpty())
     {
      try {
       String orgName = file.getOriginalFilename();
       // this line to retreive just file name 
       String 
       name=orgName.substring(orgName.lastIndexOf("\\")+1,orgName.length());
       chemin="e:\\images\\"+name;
       File file1=new File(chemin);
       file.transferTo(file1);
         } catch (IOException e) {
                                    e.printStackTrace();
                                  }

    }
    annonce.setImage(chemin);
    annonce.setTitre(prix);
    annonce.setCorps(ville);
    annonce.setPrix(cetegorie)
    annoncedao.save(annonce);
    return "SuccessAddAnnonce";
}

【问题讨论】:

    标签: spring file spring-mvc


    【解决方案1】:

    在你的类路径中添加 somename.property 文件。在其中添加以下行:

    imagepath=e:\\images;
    

    现在您在 spring 配置文件中为属性文件创建一个 bean,如下所示。

    <bean id="projectProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="locations">
            <list>
                <value>classpath*:somename.properties</value>
            </list>
        </property>
    </bean>
    

    现在在您的控制器中,添加 bean:

    @Resource(name="projectProperties")
      private Properties projectProperties;
    

    现在换行:

    chemin=projectPropertiesProperties.getProperty("imagepath")+name;
    

    【讨论】:

      【解决方案2】:

      不要在代码中使用硬编码的文件路径。使用属性文件并将其交给生产团队。因此,每当您在生产环境中部署应用程序时,只需在属性文件中更改要保存文件的文件路径即可。

      【讨论】:

      • 其实是我个人的应用。你有一个例子如何做到这一点?
      • 检查我的新答案
      猜你喜欢
      • 2015-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-01
      • 1970-01-01
      • 2021-04-05
      • 2022-01-24
      • 1970-01-01
      相关资源
      最近更新 更多