无法将上传的文件保存到特定目录

Unable to save the uploaded file into specific directory

我想上传文件并将它们保存到特定目录中 directory.And 我是文件新手 concept.When 我从我的页面上传文件,它们保存在另一个目录中(C:\Users\ROOTCP ~1\AppData\Local\Temp\multipartBody989135345617811478asTemporaryFile) 而不是指定的 directory.I 我无法设置 it.Please 帮助我找到一个 solution.For 提前感谢大家的帮助。

  public static Result uploadHoFormsByHeadOffice() throws Exception {

    Logger.info("@C HoForms -->> uploadHoFormsByHeadOffice() -->> ");
    final String  basePath = System.getenv("INVOICE_HOME");

    play.mvc.Http.MultipartFormData body = request().body()
            .asMultipartFormData(); // get Form Body

    StringBuffer fileNameString = new StringBuffer(); // to save file path
                                                        // in DB
    String formType = body.asFormUrlEncoded().get("formType")[0];// get formType from select Box
    FilePart upFile = body.getFile("hoFiles");//get the file details
    String fileName = upFile.getFilename();//get the file name
    String contentType = upFile.getContentType(); 
    File file = upFile.getFile();

    //fileName = StringUtils.substringAfterLast(fileName, ".");

    // path to Upload Files
    File ftemp= new File(basePath +"HeadOfficeForms\"+formType+"");

    //File ftemp = new File(basePath + "//HeadOfficeForms//" + formType); 
    File f1 = new File(ftemp.getAbsolutePath());// play

    ftemp.mkdirs();
     file.setWritable(true);
     file.setReadable(true);
     f1.setWritable(true);
     f1.setReadable(true);
     //HoForm.create(fileName, new Date(), formType); 

    Logger.info("@C HoForms -->> uploadHoFormsByHeadOffice() <<-- Redirecting to Upload Page for Head Office");
    return redirect(routes.HoForms.showHoFormUploadPage());
}

}

我很困惑为什么上传的文件保存在这个(C:\Users\ROOTCP~1\AppData\Local\Temp\multipartBody989135345617811478asTemporaryFile)路径

我相信当文件上传后,它会以您提供的名称存储在系统临时文件夹中。您可以将该文件复制到您喜欢的名称和位置。在您的代码中,您正在创建文件对象 f1,它似乎是您希望文件结束的位置。

您需要进行文件复制,将文件从临时文件夹复制到您想要的文件夹。可能最简单的方法是使用 apache commons FileUtils class.

File fileDest = new File(f1, "myDestFileName.txt");
try {
  FileUtils.copyFile(ftemp, fileDest);
}
catch(Exception ex) {
  ...
}

你快到了。

File file = upFile.getFile(); 是您通过表单输入获得的临时文件。您所要做的就是通过执行以下操作将此文件移动到您想要的位置:file.renameTo(ftemp).

您的代码中的问题是您在内存 ftempf1 中创建了一堆文件,但您从未对它们执行任何操作(比如将它们写入磁盘)。

此外,我建议您清理代码。很多它什么都不做(前面提到的 f1,还有你正在做 setWritable 的块)。这将使调试更容易。