在spring mvc中保存文件时的tomcat路径

时间:2013-11-11 14:53:14

标签: java eclipse spring tomcat spring-mvc

我想在tomcat目录中保存上传的文件,之后我想让一些用户访问下载该文件。 现在文件保存在eclipse目录中,或保存在eclipse中的磁盘上,但永远不会保存在tomcat目录中。我不知道如何访问tomcat的路径,我不想给: C:\ tomcat7 \ webapps \ blabla \,我想获得tomcat所在的路径。

上传控制器:

@Controller
@RequestMapping(value = "/upload")
public class UploadController
{
  @RequestMapping(method = RequestMethod.GET)
  public String getUploadForm(Model model)
  {
    model.addAttribute(new UploadItem());
    return "upload/uploadForm";
  }

  @RequestMapping(method = RequestMethod.POST)
  public String create(UploadItem uploadItem, BindingResult result)
  {
    if (result.hasErrors())
    {
      for(ObjectError error : result.getAllErrors())
      {
        System.err.println("Error: " + error.getCode() +  " - " + error.getDefaultMessage());
      }
      return "upload/uploadForm";
    }

    // Some type of file processing...

    String fileNameToCreate = "/"+uploadItem.getFileData().getOriginalFilename();
    File file;
    try {
    file = new File(fileNameToCreate);
    FileUtils.writeByteArrayToFile(file, uploadItem.getFileData().getBytes());

    } catch (Throwable e) {
    e.printStackTrace();
    } 

    System.err.println("-------------------------------------------");
    System.err.println("Test upload: " + uploadItem.getName());
    System.err.println("Test upload: " + uploadItem.getFileData().getOriginalFilename());
    System.err.println("-------------------------------------------");

    return "redirect:/app/";
  }
}

我希望有人有一些想法从这个控制器到tomcat获取路径,或者我如何修复它

1 个答案:

答案 0 :(得分:0)

您可以使用以下命令获取tomcat文件夹:

System.getProperty("catalina.base");