【问题标题】:Upload file to server directory in spring-hibernate 4在spring-hibernate 4中将文件上传到服务器目录
【发布时间】:2018-04-09 17:29:49
【问题描述】:

我正在开发 Spring hibernate 项目,我想将文件上传到服务器目录。如果我将文件保存到手动指定的目录,则文件成功上传到指定的路径。但我想要一条路径,这样当我将项目上传到云端时,我不需要做任何更改。

我尝试了“user.dir”,但它为我提供了安装 STS 的路径。但我不想要这条路。

我的控制器附在下面

public class FileUploadController {
@Autowired
private FileUploadDAO fileUploadDao;


@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public void handleFileUpload(HttpServletRequest request,
        @RequestParam CommonsMultipartFile[] fileUpload/*,@PathVariable("student_id") long student_id*/) throws Exception {

    if (fileUpload != null && fileUpload.length > 0) {
        for (CommonsMultipartFile aFile : fileUpload){

             String orginalName=aFile.getOriginalFilename();

            System.out.println("Saving file: " + orginalName);          


            File currentDirFile = new File(".");
            String helper = currentDirFile.getAbsolutePath();
            helper = helper.substring(0, helper.length()-1);
            System.out.println("helper : "+helper);



        String path= request.getServletContext().getInitParameter(helper);

        System.out.println("path : "+path);



            String path1=request.getServletContext().getContextPath();

            String finalPath=path1+File.separator+"src"+File.separator+"main"+File.separator+"webapp"+File.separator+"img"+File.separator;

            String f1=helper+finalPath;

            System.out.println("f1 : "+f1);

        File file = new File(finalPath);
        System.out.println(path);
        System.out.println(path1);
            System.out.println("finalPath : "+finalPath);


            if (!file.exists()) {
                if (file.mkdir()) {
                    System.out.println("Directory is created!");

                    String filePath = finalPath+"/"+orginalName;
                    File destination = new File(filePath);
                    //  fileUploadDao.savePath(filePath);
                            String status ="success";

                    try {
                       aFile.transferTo(destination);
                    } catch (IllegalStateException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        status="failure";
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        status="iofailure";
                    }



            System.out.println(filePath);
            fileUploadDao.save(filePath); 
            }
            else {
                System.out.println("Failed to create directory!");
            }
        }else{

            System.out.println("Directory is already exist!");

            String filePath = finalPath+orginalName;

            System.out.println("filePath : "+filePath);




            File destination = new File(f1);


            String status ="success";

            try {
               aFile.transferTo(destination);
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                status="failure";
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                status="iofailure";
            }


    System.out.println(filePath);

    fileUploadDao.save(filePath); 
    //  }


        }
    }

    //return "Success";
}   

【问题讨论】:

  • 那么你想保存当前用户目录下的所有文件吗?正确
  • 是的..但是当前目录(使用 (user.dir) 或仅 (.))向我显示 STS 安装目录。我什至尝试保存到我的 webapp 中的 img 目录,但它给出了找不到路径的异常
  • 如果我检查 img 目录的路径,它会显示相同的 STS 路径
  • 您使用的服务器是什么?部署 。原因是它走上了服务器的道路。您能在 STS 安装文件夹中确认服务器吗
  • 我正在使用 apache tomcat。我没明白你所说的“你能确认 STS 安装文件夹中的服务器”是什么意思吗?请详细说明

标签: hibernate spring-mvc


【解决方案1】:

更新:

在 AWS/Online 中,您将在路由目录或您有权访问的地方有一个文件夹(或 Create One),例如 myAppUploadedFilesmkdir /myAppUploadedFiles 。现在在您当地,您可以像这样提供 /myAppUploadedFiles/folder 。它将在 c:/myAppUploadedFiles/folderName 中创建一个文件夹。它适用于两种环境。

这就是它在生产环境中的工作方式,我们所做的就是将所有文件保存在opt\AppFiles 文件夹下。对于开发,您只需创建一个 C:\opt\AppFiles folder

这里使用/会走系统路径File file = new File("/myAppUploadedFiles/folderName");

独立于平台的更新代码,

package com.company.test;

import java.io.File;

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World.");
        System.out.println("User name "+System.getProperty("user.name"));
        File file = new File("/myAppUploadedFiles/folderName");

        if (!file.exists()) {
            if (file.mkdir()) {
                System.out.println("Directory is created!");
            } else {
                System.out.println("Failed to create directory!");
            }
        }

    }
}

【讨论】:

  • 正如我之前提到的,如果我在 C:\ 驱动器或任何其他位置手动创建一个目录并在 ...new FILE(path).. 中指定该路径.. 但是当我上传时它将如何工作我在 AWS 上的项目。我必须稍后在线制作项目,从不同机器上传文件时将存储在哪里
  • 感谢您的宝贵反馈。请检查是否有效
【解决方案2】:

您应该使用一个属性,以便您的代码与操作系统细节分离。

@Value("${file.uploads.folder}") private String fileUploadsFolder;

在您的主配置类中(假设此处为 Java 配置),然后指定属性源文件。

@Configuration @PropertySource({"classpath:application-${spring.profiles.active:dev}.properties"}) public class ApplicationContextConfig { @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } }

然后对于每个环境(例如 dev、prod),您可以使用弹簧配置文件功能并为每个弹簧配置文件创建一个 application-XXXX.properties 文件(用配置文件名称替换 XXXX)。您可以在此文件中指定路径。

应用程序-dev.properties:

file.uploads.folder=C:/temp/uploadFolder

application-prod.properties:

file.uploads.folder=/var/uploadFolder

当你启动 JVM 时不要忘记通过添加系统参数 -Dspring.profiles.active=XXXX 来指定你想要运行的 spring 配置文件

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-28
    • 2011-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多