如何使用AJAX将八位字节/流类型的Blob发送到服务器? [英] How do I send a Blob of type octet/stream to server using AJAX?

查看:117
本文介绍了如何使用AJAX将八位字节/流类型的Blob发送到服务器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直未尝试发送Blob文件(这是 .OBJ 文件类型)到使用AJAX的服务器.我希望能够在不使用输入文件字段的情况下执行此操作.我正在创建一个在线头像创建者,因此要发送到服务器的Blob文件是从最初导入到Three.js场景中的角色生成的.我已经能够将包含字符串的Blob文件发送到服务器,并将其保存到指定的文件夹(我的目标是使用Blob .OBJ文件).我曾尝试在POST请求中发送Blob之前将其转换为Base64,但这是行不通的.我要发送的文件大小为3MB.

I have unsuccessfully been trying to send a Blob file (which is an .OBJ file type) to the server using AJAX. I want to be able to do this without using an input file field. I am making an online avatar creator, so the Blob file to be sent to the server is generated from the character that is initially imported into my Three.js scene. I have been able to send a Blob file that contains a String to the server and save this to a specified folder (which I am aiming to do with the Blob .OBJ file). I have tried converting the Blob to Base64 before sending it in a POST request, but this did not work. The size of the file that I am trying to send is 3MB.

这是我的JavaScript代码,用于创建Blob文件,并使用AJAX将其发送到服务器上的PHP脚本.

Here is my JavaScript code for creating the Blob file and sending it to my PHP script on the server using AJAX.

//Create OBJ
var exporter = new THREE.OBJExporter();
var result = exporter.parse(child);

//Generate file to send to server
var formData = new FormData();
var characterBlob = new Blob([result], {type: "octet/stream"});

var reader = new FileReader();
reader.readAsDataURL(characterBlob);
reader.onloadend = function() {
formData.append('file', reader.result);

    $.ajax({
    url: "ExecuteMaya.php", // Url to which the request is send
    type: "POST",             // Type of request to be send, called as method
    data: formData, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
    processData:false,        // To send DOMDocument or non processed data file it is set to false
    contentType: false,       // The content type used when sending data to the server
    }).done(function(data) {
        console.log(data);
    });
}

这是我的PHP脚本,用于处理发送的文件.

Here is my PHP script for handling the sent file.

<?php

$sourcePath = $_FILES['file']['tmp_name'];       // Storing source path of the file in a variable
$targetPath = "upload/".$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ;    // Moving Uploaded file
echo "<span id='success'>Image Uploaded Successfully...!!</span><br/>";
echo "<br/><b>File Name:</b> " . $_FILES["file"]["name"] . "<br>";
echo "<b>Type:</b> " . $_FILES["file"]["type"] . "<br>";
echo "<b>Size:</b> " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "<b>Temp file:</b> " . $_FILES["file"]["tmp_name"] . "<br>";

?>

任何帮助将不胜感激!

更新1:var result = exporter.parse(child);是一个字符串,每当我将此变量打印到控制台时,它都需要花费几分钟的时间来加载.尝试将其发送到服务器时,此字符串的大小可能会成为问题吗?

UPDATE 1: The var result = exporter.parse(child); is a String and whenever I print this variable to the console it takes a few minutes to load. Would the size of this String be a possible issue with trying to send it to the server?

更新2:在执行PHP脚本后,此消息会打印到控制台,这使我认为PHP脚本没有将任何内容发送到服务器,或者发送的数据未正确处理.

UPDATE 2: This gets printed to the console after the PHP script has been executed, which makes me think that either nothing is being sent over to the server or the sent data is not being handled correctly by the PHP script.

图片上传成功... !!

文件名:
类型:
大小: 0 kB
临时文件:

Image Uploaded Successfully...!!

File Name:
Type:
Size: 0 kB
Temp file:

更新3:这是我要发送的文件的链接. http://www.filehosting.org/file/details/578744/CleanFemaleOBJ.obj

UPDATE 3: Here is a link to the file that I am trying to send. http://www.filehosting.org/file/details/578744/CleanFemaleOBJ.obj

您可以在TextEdit/NotePad中查看此文件以查看我要发送的字符串.它几乎是一个带有.obj扩展名的文本文件,可以将其转换为该格式,以便可以在Maya中打开.

You can view this file in TextEdit/NotePad to view the String that I want to send. It is pretty much a text file with the .obj extension to convert it to that format so it can be opened in Maya.

更新4:我现在已经更改了JavaScript代码,以便将Blob附加到FormData,而不是reader.readAsDataURL(characterBlob)的结果.

UPDATE 4: I have now altered my JavaScript code so that the Blob is appended to the FormData and not the result of reader.readAsDataURL(characterBlob).

//Create OBJ
var exporter = new THREE.OBJExporter();
var result = exporter.parse(child);

//Generate file to send to server
var formData = new FormData();
var characterBlob = new Blob([result], {type: "octet/stream"});
formData.append('file', result);                            

    $.ajax({
    url: "ExecuteMaya.php", // Url to which the request is send
    type: "POST", // Type of request to be send, called as method
    data: formData, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
    processData: false, // To send DOMDocument or non processed data file it is set to false
    }).done(function(data) {
        console.log(data);
    });

推荐答案

使用以下代码,我能够上载.obj文件.

Using the following code, I was able to upload the .obj file.

我必须增加最大上传大小,它才能正常工作.

I had to increase my maximum upload size for it to work.

您也可以考虑如下所述增加最长执行时间,但我不必这样做.

You may also think of increasing your maximum execution time as commented below, but I didn't have to.

为简单起见,我将所有内容都放在一个名为form.php的文件中.

For simplicity, I put everything in one file called form.php.

form.php

<?php
// good idea to turn on errors during development
error_reporting(E_ALL);
ini_set('display_errors', 1);

// ini_set('max_execution_time', 300);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    echo "<br/><b>File Name:</b> " . $_FILES["file"]["name"] . "<br>";
    echo "<b>Type:</b> " . $_FILES["file"]["type"] . "<br>";
    echo "<b>Size:</b> " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
    echo "<b>Temp file:</b> " . $_FILES["file"]["tmp_name"] . "<br>";
    echo "<b>Error:</b> " . $_FILES["file"]["error"] . "<br>";

    $sourcePath = $_FILES['file']['tmp_name'];          // Storing source path of the file in a variable
    $targetPath = "uploads/" . $_FILES['file']['name'];    // Target path where file is to be stored
    if (move_uploaded_file($sourcePath, $targetPath)) { // Moving Uploaded file
        echo "<span id='success'>Image Uploaded Successfully...!!</span><br/>";
    } else {
        echo "<span id='success'>Image was not Uploaded</span><br/>";
    }
    exit;
}
?>

<!DOCTYPE html>
<html>
<head>
    <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
</head>
<body>
    <form action="form.php" method="post" enctype="multipart/form-data">
        <label>File</label>
        <input type="file" name="file">
        <input type="submit" value="Upload"> 
    </form>
    <div></div>
</body>
<script>
$(function () {
    $('form').on('submit', function (e) {
        e.preventDefault();
        // logic
        $.ajax({
            url: this.action,
            type: this.method,
            data: new FormData(this), // important
            processData: false, // important
            contentType: false, // important
            success: function (res) {
                $('div').html(res);
            }
        });
    });
});
</script>
</html>

因此,首先测试一下是否可以使用上面的代码上传.obj文件.

So, first test to see if you can upload the .obj file using the code above.

在进行测试时,请打开浏览器的开发人员工具.监视网络/XHR"选项卡[ Chrome Firefox ]查看单击上传"时发出的请求

As you are testing it out, have your browser's developer tool open. Monitor your Network/XHR tab [Chrome, Firefox] to see the request that gets made when you click Upload.

如果可行,请尝试在原始代码中使用相同的逻辑.

If it works, try using the same logic in your original code.

var formData = new FormData();
formData.append('file', result);   

$.ajax({
    url: "ExecuteMaya.php",
    type: "post",
    data: formData, // important
    processData: false, // important
    contentType: false, // important!
    success: function (res) {
        console.log(res);
    }
});

同样,监视在网络/XHR"选项卡中发出的请求,并查看正在发送的内容.

Again, monitor the request made in your Network/XHR tab and look at what is being sent.

这篇关于如何使用AJAX将八位字节/流类型的Blob发送到服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆