思路:
按鈕進行隱藏,樣式自己該怎么寫怎么寫,之后通過js監測input改變上傳文件。
前端寫法:
// jquery + bootstrap寫法
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>上傳文件獲取URL</title> <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.css"> <style> .uploader{ position: relative; } .uploader input{ position: absolute; top: 4px; opacity: 0; width: 100%; } </style> </head> <body> <div class="container-fluid"> <div class="row" style="margin: 0 0;margin-top: 20px;"> <div class="col-md-1"> <div class="uploader"> <button class="btn btn-primary">上傳圖片</button> <form id="file_form"> <input type="file" id="file" name="file"> </form> </div> </div> </div> <hr> <div class="row"> </div> </div> <script src="/static/js/jquery.js"></script> <script src="/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script> <script> function start() { // 上傳文件 upload_file(); } function upload_file() { $('#file').change(function () { var data = new FormData($('#file_form')[0]); // 上傳文件 $.ajax({ url:`/v1/api/answer/kf_type/${kf_type}/upload/`, type:'post', data:data, processData:false, //表示不處理數據 contentType:false, //不設置數據類型 dataType: 'json', success:function (response) { alert(response["message"]); if (last_page_url !== ''){ get_info(last_page_url); }else{ get_info(); } // 清空文件,為下次文件上傳做准備 $('#file').val(''); } }); }) } start(); </script> </body> </html>
django后端視圖寫法:
def image_upload(req): file = req.FILES.get('file') value = file.read() return HttpResponse("ok")
// value就是文件內容
前端效果圖:
// 樣式根據自己進行調節即可,我大概寫的