javascript - 通过 Ajax 将文件从 javascript 发送到 Python

标签 javascript jquery python ajax

我在通过 ajax 调用将文件对象发送到 python 时遇到问题。
我正在使用Dropzone就像我的“文件 uploader 界面”一样,按下某个按钮时我会发送调用。

在Python中,当我尝试处理文件时,它说“'str'对象没有属性'seek'”

我的 JS 代码:

...
window.$form_add_file = $("#form_add_file");
var file = dropzone.files[0];
...

var formData = $form_add_file.serializeArray();

if(file){

    $modal_add_file.find($drop_add_file).removeClass("error");

    var filetype = file.type.split("/")[0].toLowerCase();
    var hasFile = checkFileType(filetype);
    if(!hasFile) { filetype = "file" }

    formData.push(
        { name: "file", value: file },
        { name: "file_type", value: filetype },
        { name: "file_name", value: file.name },
        { name: "file_size", value: file.size }
    );

} else {
    error = true;
    $modal_add_file.find($drop_add_file).addClass("error");
    return false;
}

if(!error){
    $.ajax({
        method: "POST",
        url: host + "json.references.new",
        data: formData,
        cache: false,
        dataType: 'json',
        success: function(data){
            if(data){
                if(data.error){
                    modalMessage($modal_add_file, data.error, "ok");
                } else {
                    refreshData(data);
                }
            }
        },
        error: function(error){
            modalMessage($modal_add_file, oops_message, "ok");
        }
    });
}

我的Python代码:

try:

    file_path = os.path.join(path, file_name)
    temp_file_path = file_path + '~'
    file.seek(0) # error happen here
    with open(temp_file_path, 'wb') as output_file:
        shutil.copyfileobj(file, output_file)
    os.rename(temp_file_path, file_path)

我一直在互联网上搜索此内容,但一无所获。

抱歉英语不好。

提前致谢!

最佳答案

seek 是文件对象的方法,而不是字符串。

我认为您的代码片段缺少一些行,但是如果 file 应该是 file_path 指向的文件,那么您应该首先使用 打开该文件>文件=打开(文件路径,'rb')。新文件对象应从第 0 个位置开始读取,因此不需要 file.seek(0)

关于javascript - 通过 Ajax 将文件从 javascript 发送到 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42401551/

相关文章:

javascript - Javascript 中的 Scratch 样式 token 字段

javascript - php中javascript按钮上的innerHTML null

jQuery 如何让选择更改以多种形式工作?

Python:为什么从线程调用的 `sys.exit(msg)` 不将 `msg` 打印到 stderr?

javascript - 如何进行 6 个以上并发 REST API 调用

javascript - Redux 过渡到 Action 执行后

javascript - bootstrap ajax内容重新出现两次

javascript - 单击(图像/按钮)将数据存储在...中以实时呈现另一个 html 模板

python - pytorch模块中的初始化类成员

javascript - WebStorm实时模板: how to create an 'export default from' live template/How to get current folder name?