我创建了一个网站,访问者可以在其中编写文本(就像Facebook或博客)。 现在我想实现访问者也可以将图像上传到网站,所以我为它添加了用户界面:“浏览”按钮和“上传”按钮。
我在客户端使用javascript / jquery,在服务器端使用python。
当用户点击浏览按钮时,如何显示选择文件的对话框?然后如何将此文件上载到服务器中的给定路径?客户端脚本可以单方面将文件上传到服务器,还是接受文件所需的服务器端脚本?
答案 0 :(得分:0)
我猜你试图异步上传这个文件,所以:
客户端
为了选择你必须在你的html中使用的文件:
<input type="file" id="file">
用户可以使用此元素选择他们的文件。现在是Javascript部分:
function upload() {
var formData = new FormData();
var target = //Upload-Server URL
formData.append("file", document.getElementById("file").files[0]);
var xhr = new XMLHttpRequest();
var eventSource = xhr.upload || xhr;
eventSource.addEventListener("progress", function(e){
var current = e.loaded || e.position ;
var total = e.total || e.totalSize;
var percant = parseInt((current/total)*100, 10);
// DO whatever you want with progress
});
xhr.open("POST", target, true);
xhr.send(formData);
xhr.onload = function() {
if (this.status === 200)
// SUCCESS
};
}
客户端
我没有使用python服务器端编码的经验,但这个http://webpython.codepoint.net/cgi_file_upload可能对您的情况有用。
答案 1 :(得分:0)
在客户端: 您可以使用HTML5 File API,它允许您创建允许用户在本地与文件交互的应用程序。基本上,您可以加载文件并在浏览器中呈现它们,而无需实际上传文件。 然后通过ajax将其发送到服务器以保存它
uploadImage(e){
var reader = new FileReader();
var url;
reader.onload = function(event){
url = event.target.result;
$('#destination').html("<img src='"+url+"' />");
//save
$.ajax('/api/image', {
cache: false,
method: 'POST',
data: {url}
});
}
//when the file is read it triggers the onload event above.
reader.readAsDataURL(e.target.files[0]);
}
这是demo
在服务器端:
image = self.request.body
import uuid
unique_filename = str(uuid.uuid4())
fh = open("images/"+unique_filename+".png", "wb")
from base64 import decodestring
fh.write(decodestring(image))
fh.close()