【发布时间】:2021-11-11 01:38:15
【问题描述】:
开发环境
wsgi、ckan、python2.7、jquery1.4使用
开发python cgi简单文件上传时出错。 Ajax 上传请求 Chrome 调试显示文件正常。 它也包含在服务器日志环境中的 wsgi.input 中。 取出该数据并将其制成临时文件 是否没有正确创建来创建 FieldStorage? FieldStorage中的所有值都是空的
HTML
<input type="file" name="add_code_linkfileup" style="display: none;">
脚本
input_file.onchange = function(){
pop_file_upload("INPUT[name ="+event.target.name+"]");
};
function pop_file_upload(target){
var form_data = new FormData();
form_data.id = "form";
form_data.enctype = 'multipart/form-data';
form_data.append('file', $(target).prop('files')[0]);
$.ajax({
type: 'POST',
url: '/api/3/custom/pop_file_upload',
dataType:'json',
data: form_data,
enctype: 'multipart/form-data',
contentType: false,
cache: false,
processData: false,
success: function(data) {
console.log('Success!');
},
beforeSend:function(){
console.log("file upload start");
},
complete:function(){
$(target).val('');
console.log("file upload end");
}
});
}
chrome调试网络
Form Data
------WebKitFormBoundaryH3daMRABWxXq3BDS
Content-Disposition: form-data; name="file"; filename="industry.jpg"
Content-Type: image/jpeg
------WebKitFormBoundaryH3daMRABWxXq3BDS--
python 源码
def read_body(self, environ):
stream = environ['wsgi.input']
length = int(environ.get('CONTENT_LENGTH', 0))
log.debug("read_body=================%s" % length)
body = TemporaryFile(mode='w+b')
while length > 0:
part = stream.read(min(length, 1024 * 200)) # 200KB buffer size
if not part: break
body.write(part)
length -= len(part)
body.seek(0)
environ['wsgi.input'] = body
return body
def pop_file_upload(self, environ, start_response):
body = self.read_body(environ)
log.debug("pop_file_upload=================%s" % body)
filefield = cgi.FieldStorage(environ=environ, fp=body, keep_blank_values=1)
log.debug("pop_file_upload=================%s" % filefield)
if isinstance(filefield, list):
# Multiple files uploaded
log.debug('<p>Check uploaded multiple images: </p>')
for fileitem in filefield:
fn = os.path.basename(fileitem.filename)
log.debug("file_name===%s"% fn)
with open("upload/{}".format(fn), 'wb') as f:
f.write(fileitem.file.read())
log.debug('<img width="200" height="auto" src="upload/{}" /><br><br>'.format(fn))
else:
# Single file uploaded
log.debug('<p>Check uploaded image: </p>')
fn = os.path.basename(filefield['file'].filename)
log.debug("file_name===%s" % fn)
with open("upload/{}".format(fn), 'wb') as f:
f.write(filefield.file.read())
log.debug('<img width="200" height="auto" src="upload/{}" />'.format(fn))
环境
'wsgi.input': <FakeCGIBody at 0x7f798f891610 viewing MultiDict([('fi...'))])>,
错误
1. `length = int(environ.get('CONTENT_LENGTH', 0))` allways zero..
* `environ.get('CONTENT_LENGTH', 0)` Notfound..return zero
2. `pop_file_upload=================FieldStorage(None, None, [])` <- empty
3. `fn = os.path.basename(filefield['file'].filename)` <- KeyError
帮助
Why can't I access the file information?
Is there anything I missed?
please give me a hint
【问题讨论】:
标签: python cgi multipartform-data