如何使用AJAX向服务器发送一个类型为octet/stream的Blob ?

时间:2022-08-19 22:11:07

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.

我一直试图使用AJAX向服务器发送一个Blob文件(它是. obj文件类型),但没有成功。我希望能够在不使用输入文件字段的情况下做到这一点。我正在创建一个在线的头像创建器,所以要发送到服务器的Blob文件是由最初导入到我的3中的字符生成的。js的场景。我已经能够将包含字符串的Blob文件发送到服务器并将其保存到指定的文件夹(我的目标是使用Blob . obj文件)。在发送POST请求之前,我尝试过将Blob转换为Base64,但这并不奏效。我要发送的文件的大小是3MB。

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

下面是创建Blob文件的JavaScript代码,并使用AJAX将其发送到服务器上的PHP脚本。

//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);
    });
}

Here is my PHP script for handling the sent file.

这是处理发送文件的PHP脚本。

<?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>";

?>

Any help would be much appreciated!

非常感谢您的帮助!

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?

更新1:var结果= exporter.parse(子);是一个字符串,每当我将这个变量打印到控制台时,加载它需要几分钟。这个字符串的大小是否会成为发送到服务器的一个可能的问题?

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.

更新2:在执行PHP脚本之后,它将被打印到控制台,这使我认为,不是没有任何东西被发送到服务器,就是PHP脚本没有正确地处理发送的数据。

Image Uploaded Successfully...!!

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

图片上传成功! !文件名:类型:Size: 0 kB Temp文件:

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

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

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.

您可以在TextEdit/NotePad中查看此文件,以查看我要发送的字符串。它基本上是一个带有.obj扩展的文本文件,可以将其转换为这种格式,这样它就可以在Maya中打开。

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).

更新4:我已经修改了JavaScript代码,使Blob附加到FormData而不是reader.readAsDataURL(characters Blob)的结果。

//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);
    });

1 个解决方案

#1


1  

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

使用以下代码,我可以上传.obj文件。

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.

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

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

为了简单起见,我把所有东西都放在一个名为form.php的文件中。

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>

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

因此,首先进行测试,看看是否可以使用上面的代码上载.obj文件。

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.

在测试时,打开浏览器的开发工具。监视您的网络/XHR选项卡[Chrome, Firefox],以查看在单击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);
    }
});

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

再次,监视您的Network/XHR选项卡中发出的请求,并查看正在发送的内容。

#1


1  

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

使用以下代码,我可以上传.obj文件。

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.

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

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

为了简单起见,我把所有东西都放在一个名为form.php的文件中。

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>

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

因此,首先进行测试,看看是否可以使用上面的代码上载.obj文件。

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.

在测试时,打开浏览器的开发工具。监视您的网络/XHR选项卡[Chrome, Firefox],以查看在单击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);
    }
});

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

再次,监视您的Network/XHR选项卡中发出的请求,并查看正在发送的内容。