2015-10-14 54 views
2

我想在一個源文件上傳我的文件,並且應該在Play框架中將該文件複製到另一個目標文件中,下面是我的代碼,請讓我知道我在做什麼錯誤,因爲它給錯誤如:錯誤:方法在類中移動文件不能應用於給定的類型;(類型文件中的方法move(Path,Path,CopyOption ...)不適用於參數(字符串,字符串,StandardCopyOption)如何在Play框架中上傳文件並複製目的地中的相同文件

public static Result upload() 
    { 
     MultipartFormData body = request().body().asMultipartFormData(); 
     FilePart uploadedFile = body.getFile("file"); 
     if (uploadedFile != null) { 
      String fileName = uploadedFile.getFilename(); 
      String contentType = uploadedFile.getContentType(); 
      File file = uploadedFile.getFile(); 
      file.renameTo(new File("D:/images/" +fileName));// it can be source 
      java.nio.file.Files.move("D:/images/", "D:/images/files/", StandardCopyOption.ATOMIC_MOVE); 
      return ok("File is uploaded at source and copied the same file at destination"); 
     } 
     else 
     {   
      return badRequest("No file is uploaded."); 
     } 
    } 

HTML:

@form(action = routes.Application.upload, 'enctype -> "multipart/form-data") { 
    <input type="file" name="file"> 
    <p> 
     <input type="submit"> 
    </p> 
    } 

回答

0

它不工作,因爲java.nio.file.Files.move使用路徑,而不是字符串:java.nio.file.Files.move(file.toPath()newFile.toPath(),StandardCopyOption。 ATOMIC_MOVE);

易於閱讀的其他不錯選擇是org.apache.commons.io.FileUtils.moveFile(file, new File(path, fileName));這個例子到move files

這段代碼沒有進行測試:

Http.MultipartFormData.FilePart uploadedFile = body.getFile("file"); 
if (uploadedFile != null) { 
    String fileName = uploadedFile.getFilename(); 
    String contentType = uploadedFile.getContentType(); 
    File file = uploadedFile.getFile(); 
    file.renameTo(new File("D:/images/" +fileName));// it can be source 

    File newFile = new File("D:/images/files/" + uploadedFile.getFilename()); 

    java.nio.file.Files.move(file.toPath(),newFile.toPath(), StandardCopyOption.ATOMIC_MOVE); 

    // org.apache.commons.io.FileUtils.moveFile(file, new File(path, fileName)); 

    return ok("File is uploaded at source and copied the same file at destination"); 
} 

希望這可以幫助

+0

感謝您的回覆,我已經嘗試了這一點,但我得到的錯誤:意外的異常:RuntimeException的:沒有HTTP上下文(來自:java.nio.file.Files.move(file.toPath(),newFile.toPath(),StandardCopyOption.ATOMIC_MOVE);) – Dhana

相關問題