CherryPy大檔案上傳

2022-07-03 23:36:11 字數 2394 閱讀 9413

和上篇檔案中介紹的cherrypy檔案上傳的主要區別在於:

示例**:

#!/usr/bin/python2.6

import cherrypy

import cgi

import tempfile

import os

class myfieldstorage(cgi.fieldstorage):

"""我們的版本使用乙個命名的臨時檔案,而不是預設

非命名檔案;保持可可見,使我們能夠上傳完畢後進一步處理"""

def make_file(self, binary=none):

return tempfile.namedtemporaryfile(delete=false)

def nobodyprocess():

"""通過設定cherrypy.request.process_request_body = false, 可以讓我們直接控制檔案的輸出

預設是載入到記憶體,我們直接輸出到磁碟"""

cherrypy.request.process_request_body = false

cherrypy.tools.nobodyprocess = cherrypy.tool('before_request_body', nobodyprocess)

class fileupload:

@cherrypy.expose

def index(self):

"""簡單的html上傳form"""

return """""

@cherrypy.expose

@cherrypy.tools.nobodyprocess()

def upload(self, thefile=none):

"""上傳action"""

# 大檔案傳輸可能需要很長的時間,cherrypy預設的響應時間是300s,在這裡我們設定為1小時。

cherrypy.response.timeout = 3600

# 將請求頭的key轉換為小寫

lchdrs = {}

for key, val in cherrypy.request.headers.iteritems():

lchdrs[key.lower()] = val

# 可以在這裡限制上傳內容的長度...

# incomingbytes = int(lchdrs['content-length'])

# 使用自定義的filedstorage分析編碼後的form資料,包括上傳的檔案

formfields = myfieldstorage(fp=cherrypy.request.rfile,

headers=lchdrs,

environ=,

keep_blank_values=true

thefile = formfields['thefile']

os.link(thefile.file.name, '/tmp/'+thefile.filename)

return "ok, got it filename='%s'" % thefile.filename

# 去除請求body大小限制,cherrypy預設大小為100mb

cherrypy.server.max_request_body_size = 0

# 設定socket連線超時時間,cherrypy預設為10s

cherrypy.server.socket_timeout = 60

cherrypy.quickstart(fileupload())

注意:

使用fieldstorage,當檔案大小小於1000位元組時,其不是使用fieldstorage的make_file儲存成檔案,而是使用記憶體檔案物件(cstringio/stringio)儲存。核心改進**如下:

if formfields.has_key('thefile'):

thefile = formfields['thefile']

else:

print 'no thefile field'

return 'error'

if not thefile.file:

print "error: not a file upload."

return 'error'

elif not hasattr(thefile.file, 'name'): #手動處理小檔案

name = tempfile.mktemp()

with open(name, 'wb') as f:

f.write(thefile.file.read())

else:

name = thefile.file.name

os.link(name, '/tmp/'+thefile.filename)

CherryPy大檔案上傳

和上篇檔案中介紹的cherrypy檔案上傳的主要區別在於 示例 usr bin python2.6 import cherrypy import cgi import tempfile import os class myfieldstorage cgi.fieldstorage 我們的版本使用乙個...

上傳大檔案 關於大檔案上傳

js計算檔案md5使用spark md5.js,據說這個庫使用的是世界上最快的md5演算法。js對檔案切片並使用ajax上傳切片 let size file.size 獲取檔案大小 const shardsize 1024 1024 塊大小1mb let shardcount math.ceil s...

大檔案上傳

首先先要建好幾個檔案 html裡面 1238 9141589 90php裡面 1 2 username post username 3 1 接收前端傳過來的引數 4 ori file name post filename 原始檔案的檔名 5 file files file 6 tmp name fi...