【问题标题】:Image uploading to website with jquery/python使用 jquery/python 将图像上传到网站
【发布时间】:2013-07-28 10:35:03
【问题描述】:

我创建了一个网站,访问者可以在其中写文字(就像 Facebook 或博客)。 现在我想实现访问者也可以将图像上传到站点,因此我为其添加了用户界面:“浏览”按钮和“上传”按钮。

我在客户端使用javascript/jquery,在服务器端使用python。

当用户单击浏览按钮时,如何使选择文件的对话框出现?然后如何将该文件上传到服务器中的给定路径?客户端脚本可以单方面上传文件到服务器还是需要服务器端脚本来接受文件?

【问题讨论】:

    标签: jquery python image uploading


    【解决方案1】:

    我猜你正在尝试异步上传这个文件,所以:

    客户端

    为了选择您必须在 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 可能对你有用。

    【讨论】:

      【解决方案2】:

      在客户端: 您可以使用 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()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-01-19
        • 2019-03-22
        • 2016-04-14
        • 1970-01-01
        • 1970-01-01
        • 2012-10-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多