使用情景
製作詞雲, 並在手機上顯示
效果展示吳孟達先生今日走了, 用先生的百度百科做個詞雲, 紀念小時候的大明星達叔
原理使用python的wordcloud模組生成詞雲autojs負責展示詞雲難點django實現檔案的上傳和下載autojs實現多檔案上傳程式碼講解畫一個介面用於功能演示let 吳孟達先生的百度百科 = "......"ui.input.setText(吳孟達先生的百度百科);
ui.btn.click(function () { ui.btn.setEnabled(false); ui.btn.setText("伺服器生成詞雲中, 請耐性等待"); threads.start(function () { let url = "http://192.168.101.4:8000/polls/wordcloud/"; var res = http.postMultipart(url, getData()); let tempFilepath = "/sdcard/1.jpg"; files.writeBytes(tempFilepath, res.body.bytes()); // app.viewFile(tempFilepath); ui.post(function () { ui.img.attr("src", "file://" + tempFilepath); ui.btn.setEnabled(true); ui.btn.setText("生成詞雲"); }, 100); });});
展示處理好的詞雲圖片
ui.img.attr("src", "file://" + tempFilepath);
伺服器端使用django搭建檔案上傳下載服務定義生成詞雲的函式def wordcloud(request): files = request.FILES.getlist('file') background_image = request.FILES.get('background_image.jpg') 詞雲來源 = request.FILES.get('詞雲來源.txt') for f in files: print(f) if(not (background_image and 詞雲來源)): return HttpResponse("需要背景圖片和詞雲來源") if(background_image.size > 10000 and background_image.size < 1024 * 1024 * 3 and 詞雲來源.size > 10 and 詞雲來源.size < 1024 * 1024 * 5): handle_uploaded_file(background_image) handle_uploaded_file(詞雲來源) imgpath = createwordcloud.create() result = download_api(imgpath) return HttpResponse(result) else: return HttpResponse("不符合大小限制")
處理前端傳過來的圖片def handle_uploaded_file(f): root_dir = os.path.dirname(os.path.abspath('.')) with open(father_path + '/res/' + f.name, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) return father_path + '/res/' + f.name
將生成的詞雲圖片響應給前端
def download_api(filepath): file = open(filepath, 'rb') response = HttpResponse(file) # 設定頭資訊,告訴瀏覽器這是個檔案 response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = 'attachment;filename="wordcloud.jpg"' return response