2015-10-07 29 views
2

文件Uppload中的CherryPy:的CherryPy得到上傳文件的臨時位置

def upload(self, myFile): 
     out = """File name: %s, Content-Type: %""" 
     return out % (myFile.filename, myFile.content_type) 
    upload.exposed = True 

docs

當客戶端上傳文件到CherryPy的應用程序,它立即放在 盤。 CherryPy會將其作爲 參數傳遞給您公開的方法(請參閱下面的「myFile」);該arg將具有「文件」屬性 ,該文件是臨時上傳文件的句柄。如果您希望 永久保存文件,則需要從myFile.file中讀取(),並在其他位置讀取write()。

如何獲取上傳文件的臨時位置?

回答

1

使用默認實體處理器無法獲取臨時文件的名稱。但是你可以設置你自己定製的一個來確保總是創建一個臨時文件(通常不是爲文件< 1000字節創建的)。

要在臨時文件的名稱,你需要它與CustomPart類創建的NamedTemporaryFile

import tempfile 
import cherrypy as cp 

class App: 

    @cp.expose 
    def index(self): 
     return """ 
     <html><body> 
      <h2>Upload a file</h2> 
      <form action="upload" method="post" enctype="multipart/form-data"> 
      filename: <input type="file" name="my_file" /><br /> 
      <input type="submit" /> 
      </form> 
     </body></html> 
     """ 

    @cp.expose 
    def upload(self, my_file): 
     return "The path is %s" % my_file.file.name 


class CustomPart(cp._cpreqbody.Part): 
    """ 
    Custom entity part that it will alway create a named 
    temporary file for the entities. 
    """ 
    maxrambytes = 0 # to ensure that it doesn't store it in memory 

    def make_file(self): 
     return tempfile.NamedTemporaryFile() 


if __name__ == '__main__': 
    cp.quickstart(App(), config={ 
     '/': { 
      'request.body.part_class': CustomPart 
     } 
    }) 

當請求被默認的NamedTemporaryFile因爲做你可能無法看到該文件類在關閉時立即刪除文件。在這種情況下,只要請求完成。你可以添加一些睡眠電話這樣和驗證我剛纔說:

@cp.expose 
    def upload(self, my_file): 
     import time 
     cp.log.error("You have 30 seconds to open the temporary file %s" % my_file.file.name) 
     time.sleep(30) 
     return "The path is %s" % my_file.file.name 

如果你真的想保存臨時文件,那麼你只需要在delete參數設置爲FalseNamedTemporaryFile並結束了像這樣:

class CustomPart(cp._cpreqbody.Part): 
     """ 
     Custom entity part that it will alway create a named 
     temporary file for the entities. 
     """ 
     maxrambytes = 0 # to ensure that it doesn't store it in memory 

     def make_file(self): 
      return tempfile.NamedTemporaryFile(delete=False) 

你必須確保你自己刪除這些臨時文件。