python flask 文件上传接口

  from flask import Flask,request,redirect,json
from werkzeug.utils import secure_filename
import os
UPLOAD_FOLDER = './'  #文件存放路径
ALLOWED_EXTENSIONS = set(['jpg','html']) #限制上传文件格式

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 5 * 1024 * 1024
#提前访问跨域
@app.after_request
def after_request(response):
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization,session_id')
    response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS,HEAD')
    # 这里不能使用add方法,否则会出现 The 'Access-Control-Allow-Origin' header contains multiple values 的问题
    response.headers['Access-Control-Allow-Origin'] = '*'
    return response

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        # submit an empty part without filename
        if file.filename == '':
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return json.dumps("{'data':1}",ensure_ascii=False)
        else:
            return json.dumps("{'data':0}", ensure_ascii=False)
    else:
        return json.dumps("{'data':0}", ensure_ascii=False)


<!DOCTYPE html>
<html>
<html>
<head>
  <meta charset="utf-8">
<title>接口测试</title>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.0.js">
</script>

    <script type="text/jscript">

       $(function () {
           $("#btn_uploadimg").click(function () {
               var fileObj = document.getElementById("FileUpload").files[0]; // js 获取文件对象
               if (typeof (fileObj) == "undefined" || fileObj.size <= 0) {
                   alert("请选择图片");
                   return;
               }
               var formFile = new FormData();
               formFile.append("action", "UploadVMKImagePath");
               formFile.append("file", fileObj); //加入文件对象

               
               // ajax 提交

               var data = formFile;
               $.ajax({
                   url: "http://127.0.0.1:5000",
                   data: data,
                   type: "Post",
                   dataType: "json",
                   cache: false,//上传文件无需缓存
                   processData: false,//用于对data参数进行序列化处理 这里必须false
                   contentType: false, //必须
                   success: function (result) {
                   console.log(result)
                      data=eval('(' + result + ')')['data'];
                   console.log(data);
				   if(data=='1'){
                      alert("上传完成!");
                   }else{
				   alert("上传失败!");
				   }
                   }
               })
			
           })
       })

   </script>
</head>

<div  >
       <input type="file" name="FileUpload" id="FileUpload">
       <button  class="layui-btn layui-btn-mini" id="btn_uploadimg">上传图片</button>
</div>
</html>


评论

刷新

友情链接