flask request files save zip

Solutions on MaxInterview for flask request files save zip by the best coders in the world

showing results for - "flask request files save zip"
Kevin
01 Sep 2019
1@app.route("/upload", methods=["GET", "POST"])
2def upload():
3    if request.method == "GET":
4        return render_template("upload.html")
5    obj = request.files.get("file")
6    print(obj)  # <FileStorage: "test.zip" ("application/x-zip-compressed")>
7    print(obj.filename)  # test.zip
8    print(obj.stream)  # <tempfile.SpooledTemporaryFile object at 0x0000000004135160>
9         # Check if the suffix name of the uploaded file is zip
10    ret_list = obj.filename.rsplit(".", maxsplit=1)
11    if len(ret_list) != 2:
12                 return "Please upload zip file"
13    if ret_list[1] != "zip":
14                 return "Please upload zip file"
15 
16         # Method 1: Save the file directly
17    obj.save(os.path.join(BASE_DIR, "files", obj.filename))
18 
19         # Method 2: Save the decompressed file (the original compressed file is not saved)
20    target_path = os.path.join(BASE_DIR, "files", str(uuid.uuid4()))
21    shutil._unpack_zipfile(obj.stream, target_path)
22 
23         # Method three: Save the compressed file locally, then decompress it, and then delete the compressed file
24         file_path = os.path.join(BASE_DIR, "files", obj.filename) # The path where the uploaded file is saved
25    obj.save(file_path)
26         target_path = os.path.join(BASE_DIR, "files", str(uuid.uuid4())) # The path where the unzipped files are saved
27    ret = unzip_file(file_path, target_path)
28         os.remove(file_path) # delete file
29    if ret:
30        return ret
31    
32         return "Upload successful"
33