使用粘贴操作将文件上载到服务器

时间:2016-07-12 20:43:28

标签: javascript python javascript-events flask-wtforms

我一直在尝试将从用户剪贴板中捕获的图像文件上传到服务器(通过Flask实现的网页)。到目前为止,我有以下代码(几乎逐字逐句从另一个SO帖子中解除):

<script type="text/javascript">
// We start by checking if the browser supports the 
// Clipboard object. If not, we need to create a 
// contenteditable element that catches all pasted data 

// Add the paste event listener
console.log("Start");
if (window.addEventListener) {
    console.log("new event listener");
    window.addEventListener("paste", pasteHandler);
    }
else if (window.attachEvent) {
    console.log("old event listener");
    window.attachEvent("onpaste", pasteHandler);
    }
console.log("End");

/* Handle paste events */
function pasteHandler(e) {
    console.log("in paste handler");
   // We need to check if event.clipboardData is supported (Chrome)
   if (e.clipboardData) {
        console.log("in clip data");
      // Get the items from the clipboard
      var items = e.clipboardData.items;
      if (items) {
         // Loop through all items, looking for any kind of image
         for (var i = 0; i < items.length; i++) {
            if (items[i].type.indexOf("image") !== -1) {
                console.log("image exists in clipboard");
               // We need to represent the image as a file,
               var blob = items[i].getAsFile();
               // and use a URL or webkitURL (whichever is available to the browser)
               // to create a temporary URL to the object
               var URLObj = window.URL || window.webkitURL;
               var source = URLObj.createObjectURL(blob);
               var form = document.forms['addbug'];
               var fd = new FormData(form);    
               fd.append('attach',blob);
               console.log("image added to form");
               }
            }
        }
    }
}
</script>

我正在努力解决的部分是将捕获的流保存在服务器上。我试图使用以下python代码将文件存储在服务器上:

if form.validate_on_submit():
    print('in submit')
    if request.method == 'POST':
        print('in post')
        if 'attach' in request.files:
            print('in attach')
            upload_file = request.files['attach']
            print('upload file = '+str(upload_file))
            print(upload_file.filename)
            if allowed_file(upload_file.filename):
                filename =  secure_filename(upload_file.filename)
                upload_file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
                file_loc = os.path.join(app.config['UPLOAD_FOLDER'], filename)

我在最后一个印刷声明中得到的是:

upload file = <FileStorage: '' ('application/octet-stream')>

听起来像是一个流而不是一个文件。我认为upload_file.save不起作用,因为它不能将输入识别为文件,但我不知道如何(可能)将八位字节流数据转换为可读文件。或者我可能需要以不同方式读取blob而不是使用getAsFile()?有什么想法吗?

0 个答案:

没有答案