flask jQuery ajax upload file

1. html code

 <div>
        <form id="uploadForm" enctype="multipart/form-data" >
            <div>
                <input type="file" name="file" value="" style="color: white">
                <input type="button" value="上传" id="upFileBtn">
            </div>
        </form>
  </div>
    

Note: 1. The html part is mainly a form, in which enctype = "multipart/form-data" of the form must be present.

  2. Since the background color of my page is set to black, the font color is white, which is harmless.

 

var up_file = function () {
 var formData = new FormData($('#uploadForm')[0 ]);
$.ajax({
    url:"/test/up_file",
    type: "POST",
    data: formData,
    async: true,
    cashe: false,
    contentType:false,
    processData:false,
    success:function (returndata) {
        alert(returndata)  },   error: function (returndata) { 


     alert("Upload failed!") 

  })

 Note: If you want to upload a file with ajax, you need to use FormData to convert the file into a FormData object.

3. The flask part

@trading_date.route('/up_file', methods=['GET', 'POST'])
def up_file():
    if request.method == "POST":
        file = request.files['file']
       #  file_name = "test.csv"
       file_name = file.filename
        file.save(os.path.join('templates\\files', file_name))

        return  ' Upload successful '

Note: 1. This article does not write out the blueprint. I believe that the configuration of routing is not difficult.

  2. This code saves the file in the files folder under the templates of the server. You can directly give the file a new name, or you can use rerquest.files['file'].filename to get the name of the uploaded file.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324861503&siteId=291194637