上传文件Ajax来的CherryPy [英] Uploading a file in ajax to CherryPy

查看:724
本文介绍了上传文件Ajax来的CherryPy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一次上传多个文件到我的CherryPy服务器。

I am trying to upload many files at once to my CherryPy server.

我下面本教程显示PHP的code服务器端。

I am following this tutorial that shows PHP code on the server side.

JavaScript的部分是简单的。这里是做什么的总结:

The JavaScript part is simple. Here is a summary of what it does:

function FileSelectHandler(e) {
  var files = e.target.files || e.dataTransfer.files;
  for (var i = 0, f; f = files[i]; i++) {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "upload", true);
    xhr.setRequestHeader("X_FILENAME", file.name);
    xhr.send(file);
}

我翻译的 upload.php的在本教程中介绍到的东西是这样的:

I translated the upload.php described in the tutorial into something like this:

def upload(self):
    [...]

当服务器收到请求我可以看到 cherrypy.request.headers ['的Content-Length'] = = 5676 这是我想上传文件的长度,所以我想整个文件已发送到服务器。

When the server receives the request I can see that cherrypy.request.headers['Content-Length'] == 5676 which is the length of the file I'm trying to upload, so I assume the whole file has been sent to the server.

我如何获取该文件的内容?

How do I get the content of the file?

推荐答案

目前最小,它看起来像下面这样。经过测试,在Firefox和铬。如果你需要支持传统的浏览器我想看看对于polyfills和备用一些JavaScript库。

At its minimum it looks like the following. Tested in Firefox and Chromium. If you need to support legacy browsers I'd look at some JavaScript library for polyfills and fallback.

#!/usr/bin/env python
# -*- coding: utf-8 -*-


import os
import shutil

import cherrypy


config = {
  'global' : {
    'server.socket_host' : '127.0.0.1',
    'server.socket_port' : 8080,
    'server.thread_pool' : 8,
  }
}


class App:

  @cherrypy.expose
  def index(self):
    return '''<!DOCTYPE html>
      <html>
      <head>
        <title>CherryPy Async Upload</title>
      </head>
      <body>
        <form id='upload' action=''>
          <label for='fileselect'>Files to upload:</label>
          <input type='file' id='fileselect' multiple='multiple' />
        </form>
        <script type='text/javascript'>
          function upload(file)
          {
            var xhr = new XMLHttpRequest();

            xhr.upload.addEventListener('progress', function(event) 
            {
              console.log('progess', file.name, event.loaded, event.total);
            });
            xhr.addEventListener('readystatechange', function(event) 
            {
              console.log(
                'ready state', 
                file.name, 
                xhr.readyState, 
                xhr.readyState == 4 && xhr.status
              );
            });

            xhr.open('POST', '/upload', true);
            xhr.setRequestHeader('X-Filename', file.name);

            console.log('sending', file.name, file);
            xhr.send(file);
          }

          var select = document.getElementById('fileselect');
          var form   = document.getElementById('upload')
          select.addEventListener('change', function(event)
          {
            for(var i = 0; i < event.target.files.length; i += 1)
            {
              upload(event.target.files[i]); 
            }
            form.reset();
          });
        </script>
      </body>
      </html>
   '''

  @cherrypy.expose
  def upload(self):
    '''Handle non-multipart upload'''

    filename    = os.path.basename(cherrypy.request.headers['x-filename'])
    destination = os.path.join('/home/user', filename)
    with open(destination, 'wb') as f:
      shutil.copyfileobj(cherrypy.request.body, f)


if __name__ == '__main__':
  cherrypy.quickstart(App(), '/', config)

这篇关于上传文件Ajax来的CherryPy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆