簡單實現圖片上傳並保存html+flask(順便解決跨域問題)

廢話不多說,直接上代碼
1、html文件內容

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <script src="./jquery.min.js"></script>
    <script src="./jquery.form.js"></script>
</head>
<body>
    <form id="imageForm" enctype="multipart/form-data" method="POST">
        <input type="file" name="file"/>
        <button type="submit">上傳dddd</button>
    </form>
    <div id="head"><p>圖片內容</p></div>
    <div id="content1"></div>
    <script>
        var ajax_option={
            url: "http://ip:port/upload",
            accept: "image/png,image/jpeg",
            dataType: "json",
            clearFomr: true,
            resetFomr: true,
            timeout: 3000,
            xhrFields: {
                withCredentials: true    // 前端設置是否帶cookie
            },
            success:function(responseText,statusText,xhr,$form){
                alert('lalala');
                console.log(responseText);
                console.log(xhr);
            },
        };
        $('#imageForm').submit(function(){
            $("#imageForm").ajaxSubmit(ajax_option);
            return false;
        })

</script>
</body>
</html>

2、nginx啓動服務,location內index設置成index.html;(nginx其他配置自行解決)
3、flask

def af_request(resp):
    resp = make_response(resp)
    resp.headers['Access-Control-Allow-Credentials'] = 'true'
    resp.headers['Access-Control-Allow-Origin'] = request.environ['HTTP_ORIGIN']
    resp.headers['Access-Control-Allow-Methods'] = 'GET,POST'
    resp.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return resp

@app.route('/upload', methods=['POST'])
def upload():
    dir = os.path.abspath('.')
    path = '{}/{}'.format(dir,'imgs')
    if not os.path.exists(path):
        os.mkdir(path,0755)
    file = request.files['file']
    name = file.filename
    filename = int(time.time())
    filetype = name.split('.')[-1]
    file.save('{}/{}.{}'.format(path, filename, filetype))
    return resp_json('')
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章