前端代码
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<div style="width:100px;float:left;margin-left:35px;">
<form method="post" enctype="multipart/form-data" id="test_form" style="margin-top:45px;">
<a href="javascript:;" class="file button red">选择照片
<input type="file" name="photo" id="photo">
</a>
<!-- <a type="button" class="file button red" id="tj" οnclick="ajaxForm()">上传照片</a>-->
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<!-- 用$符号就要用这句-->
<img crossorigin="anonymous" >
<script>
function ajaxForm(){
var form= new FormData(document.getElementById("test_form"));
$.ajax({
url:"http://30.43.122.45:5001/up_photo",
type:"post",
data:form,
dataType: 'json',
processData:false,
contentType:false,
// success:function(data){
// document.write(Date());
// },
success:function(){
document.write(Date());
},
error:function(e){
alert("error");
}
})
}
</script>
<button type="button" onclick="ajaxForm()">上传照片</button>
</form>
</div>
</body>
后端代码
import warnings
import requests
import numpy as np
warnings.filterwarnings("ignore")
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
#------------------------------
from flask import Flask, jsonify, request, make_response
import argparse
app = Flask(__name__)
#------------------------------
#------------------------------
#Service API Interface
@app.route('/')
def index():
return '<h1>Hello, world!</h1>'
@app.after_request
#跨域不加会报错
#ajax:No 'Access-Control-Allow-Origin' header is present on the requested
def cors(environ):
environ.headers['Access-Control-Allow-Origin']='*'
environ.headers['Access-Control-Allow-Method']='*'
environ.headers['Access-Control-Allow-Headers']='x-requested-with,content-type'
return environ
@app.route('/up_photo', methods=['POST'], strict_slashes=False)
def api_upload():
# file_dir = os.path.join(basedir, app.config['UPLOAD_FOLDER'])
# if not os.path.exists(file_dir):
# os.makedirs(file_dir)
f = request.files['photo']
print(f)
# return jsonify({"success": 200, "msg": "上传成功"})
return jsonify({"success": 200, "msg": "上传成功"})
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'-p', '--port',
type=int,
default=5001,
help='Port of serving api')
args = parser.parse_args()
app.run(host='0.0.0.0', port=args.port)