将 ajax 文件上传到 CherryPy [英] Uploading a file in ajax to CherryPy

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

问题描述

我正在尝试一次将多个文件上传到我的 CherryPy 服务器.

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

我正在关注在服务器端显示 PHP 代码的 本教程.

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.

如何获取文件内容?

推荐答案

至少看起来像下面这样.在 Firefox 和 Chromium 中测试.如果您需要支持旧版浏览器,我会查看一些用于 polyfill 和回退的 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天全站免登陆