【问题标题】:Is it possible to upload data from javascript to the server?是否可以将数据从 javascript 上传到服务器?
【发布时间】:2019-09-21 19:20:15
【问题描述】:

我有一段 javascript 代码,它通过画布上构建的编辑器生成 .jpeg。我想将.jpeg 传输到服务器并将文件保存在服务器上。到目前为止,我设法使用 HTML POST 将文件从客户端发送到服务器。但我似乎无法从 javascript 中完成它。

既然javascript无法访问客户端的文件系统,那么如何从javascript获取数据到服务器呢?

我使用下面的代码将文件从客户端发送到服务器。

<form method="post" action="" enctype="multipart/form-data" id="myform">
  <div >
    <input type="file" id="file" name="file" />
    <input type="button" class="button" value="Upload" id="but_upload">
  </div>
</form>

<script type="text/javascript">
   jQuery(document).ready(function() {
     jQuery("#but_upload").click(function() {
       var fd = new FormData();
       var files = jQuery('#file')[0].files[0];
       fd.append('file', files);

       jQuery.ajax({
          url: 'http://localhost:1234/wordpress/wpcontent/themes/twentyseventeen/upload.php',
          type: 'post',
          data: fd,
          contentType: false,
          processData: false,
          success: function(response){
             if(response != 0){
                 alert('file uploaded');
                }
                 else{
                   alert('file not uploaded');
                }
            },
        });
    });
 });
</script>

【问题讨论】:

  • 这不行吗?你有什么错误吗?
  • wordpress ajax 的正常方法是添加一个操作并使用 wp 文档中概述的 wp-admin ajax url
  • 从客户端驱动器发送文件时它确实有效。从 js 中发送变量时不会。

标签: javascript php upload


【解决方案1】:

您必须以多部分请求的形式向服务器发送图像(在正文中发送文件),搜索how to create a upload route in server

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-12
    • 2018-04-12
    • 2014-12-09
    • 1970-01-01
    相关资源
    最近更新 更多