weixin_33694620 2018-07-11 09:33 采纳率: 0%
浏览 111

使用FormData发送文件[重复]

This question already has an answer here:
                </div>
            </div>
                    <div class="grid--cell mb0 mt4">
                        <a href="/questions/25674322/post-values-from-an-html-form-and-access-them-in-a-flask-view" dir="ltr">Post values from an HTML form and access them in a Flask view</a>
                            <span class="question-originals-answer-count">
                                (1 answer)
                            </span>
                    </div>
            <div class="grid--cell mb0 mt8">Closed <span title="2018-07-11 13:20:18Z" class="relativetime">2 years ago</span>.</div>
        </div>
    </aside>

I am trying to add new feature to my web application, to make file uploads avaliable.

Tech: Flask, Python 3. I am using ajax an object FormData, but it doesn't work. Can’t send file to server.

Function ajax() in javascript causes error 400.I have tried to add a form in html and to use FormData(form). But it didn't change anything.

html

<label for="new-homework" class="add">Add</label>
    <button class="send">Submit</button>
    <input type="file" style="visibility:hidden;" multiple id="new-homework" value="Choose files">

javascript

function ajax(type, url, data, callback) { 
    var f = callback || function (data) {};
    var request = new XMLHttpRequest();
    request.onreadystatecheng = function () {
        if(request.readyState == 4 && request.status == 200){
            console.log('Success');
        }
    }
    request.open(type, url);
    if(type == 'POST')
        request.setRequestHeader('Content-type','application/json; charset=utf-8');
    console.log(data);
    request.send(data);    // Issue is here
}

var nf_button = document.getElementById("new-homework");
nf_button.addEventListener("change", function() {
    console.log('working');
    var files = nf_button.files;
    canSendFiles(files);
}, false);

function canSendFiles(files) {
    document.querySelector('button.send').onclick = function () {
        var form = new FormData();
        form.append('homework', files);
        console.log(form.getAll('homework'));
        ajax('POST', '/upload_file', form, function () {
            console.log('Sent');    
        });
    }
}

python

 UPLOAD_FOLDER = "C:\chess_school\pa\saved"
    ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif',
                              'TXT', 'PDF', 'PNG', 'JPG', 'JPEG', 'GIF']
                             )


    @app.route('/upload_file', methods=['GET', 'POST'])
    def upload_file():
        """
        Files upload

        :return:

        """
        if request.method == 'POST':
            file = request.files['file']
            print(file)
            if file and allowed_file(file.filename):
                filename = secure_filename(file.filename)
                path = app.config['UPLOAD_FOLDER']
                if not os.path.exists(path):
                    os.makedirs(path)
                file.save(os.path.join(path, filename))
                return redirect(url_for('uploaded_file',
                                        filename=filename))
        return '''
        <!doctype html>
        <title>Upload new File</title>
        <h1>Upload new File</h1>
        <form action="" method=post enctype=multipart/form-data>
          <p><input type=file name=file>
             <input type=submit value=Upload>
        </form>
        '''


    @app.route('/uploads/<filename>')
    def uploaded_file(filename):
        return send_from_directory(app.config['UPLOAD_FOLDER'],
                                   filename)

What's wrong? How to fix it?

Any help will be appreciated!

</div>
  • 写回答

1条回答 默认 最新

  • 北城已荒凉 2018-07-11 12:10
    关注

    I am not quite sure as I'm a newbie as well, but I have a feel like you are missing the name in your HTML.

    HTML

    <input type="file" style="visibility:hidden;" multiple id="new-homework" value="Choose files" name="file">
    

    Python

    if request.method == 'POST':
                file = request.files['file']
                print(file)
    

    Thanks.

    评论

报告相同问题?

悬赏问题

  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行