前端通过AJAX收集文件传输到python服务器指定目录文件夹中
1.前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>excel URL地址图片下载器</title>
</head>
<body>
<div style="width: 90%;margin: 0 auto;margin-top: 50px">
<form>
<div class="form-group">
<h3><label for="exampleInputEmail1">请输入您Excel中的唯一列名作为下载图片的名称:</label></h3>
<input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"> </div>
<div class="form-group">
<h3><label for="exampleInputPassword1">请输入Excel中图片URL列的列名:</label></h3>
<input type="password" class="form-control" id="exampleInputPassword1">
</div>
<form>
<input type="file" name="file" id="file"/><br><br><br><input type="file" name="files" id="files"/><br>
<button style="width: 300px;margin-top: 15px" type="submit" class="btn btn-outline-success"
onclick="upload_file()">点击上传Excel文本文件
</button>
</form><button style="width: 300px ;margin-top: 15px" type="button" class="btn btn-outline-info">点击下载图片到本地</button>
</form>
</div>
</body>
</html>
<script>
$(function () {
$('#file').change(function (e) {
console.log("数据来了")
var files = e.target.files;
var formFile = new FormData();
formFile.append("file", files[0]);
$.ajax({
url: "/upload/",
data: formFile,
type: "post",
dataType: "json",
cache: false,
processData: false,
contentType: false,
success: function (result) {
alert("上传完成!!!");
},
})
})
})
function upload_file(){
var formData = new FormData();
var name = $("#files").val();
console.log("文件路径是:",name)
formData.append("file", $("#files")[0].files[0]);
formData.append("name", name);
$.ajax({
url: '/upload_two/',
type: 'POST',
async: false,
data: formData,
processData: false,
contentType: false,
beforeSend: function () {
console.log("正在进行,请稍候");
},
success: function (d) {
alert("上传完成!!!")
}
})
}
</script>
2.python flask应用程序
@app.route('/upload_two/',methods=['GET','POST'])
def upload_files():
if request.method == 'POST':
f = request.files['file']
basepath = os.path.dirname(__file__)
print(f.filename)
file_name = str(round(time.time() * 1000))
dir = str(time.strftime('%y%m%d', time.localtime()))
upload_path = os.path.join(basepath, 'static/upload/' + dir)
if not os.path.exists(upload_path):
os.mkdir(upload_path)
file_path = str(file_name) + str(f.filename)
f.save(upload_path + "/" + file_path)
return Response(json.dumps(file_path), mimetype='application/json')