1. 程式人生 > >play框架之檔案上傳

play框架之檔案上傳

<span style="font-size:18px;"><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <form action="/upload.do" method="POST" enctype="multipart/form-data">
        <input type="file" name="myfile">
        <input type="submit"/>
    </form>
</body>
</html></span>

routes路由表 post    /upload.do      controllers.xxx.upload

後臺實現:

<span style="font-size:18px;">public static Result upload() throws IOException{
		MultipartFormData body = request().body().asMultipartFormData();
		  FilePart filepart = body.getFile("myfile");
		  if (filepart != null) {
		    String fileName = filepart.getFilename();
		    String contentType = filepart.getContentType(); 
		    File file = filepart.getFile();//獲取到預設上傳儲存的完整檔案路徑,這只是個臨時檔案
		    BufferedInputStream is=new BufferedInputStream(new FileInputStream(file));
		    File newFile=new File("e://upload/"+filepart.getFilename());//要儲存的檔案路徑
		    BufferedOutputStream os=new BufferedOutputStream(new FileOutputStream(newFile));
		    byte[] b = new byte[1024]; 
		    while(is.read(b)!=-1){
		    	os.write(b);
		    }
		    is.close();
		    os.close();
		    return ok("File uploaded");
		  } else {
		    flash("error", "Missing file");
		    
		    return ok("aa");    
		  }
	}</span>