因此,我一直在尝试使用FormData通过$ http服务发送音频文件,到目前为止,我尝试发送的文件尚未奏效。
服务的外观如下:
songs_services.add_new_song = function(new_song_name, new_song_artist, song) {
var fd = new FormData();
fd.append("new_song_name", new_song_name);
fd.append("new_song_artist", new_song_artist);
fd.append("song", song);
console.log(fd.get("new_song_name"));
console.log(fd.get("new_song_artist"));
console.log(fd.get("song"));
return $http.post(BACKEND_PREFIX + "add_new_song", fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).then(function() {
}, function() {
});
};
我想确保信息实际上已附加到我的FormData中,这就是我在控制台中得到的信息:
所以现在我知道FormData实际上具有我需要的信息。
我也曾尝试将Content-Type更改为multipart / form-data,但也没有成功。
我还使用CakePHP 2作为后端,因此这就是我尝试获取信息的方式:
public function add_new_song() {
$this->autoRender = false;
$data = json_decode(file_get_contents("php://input"));
print_r($data);
print_r($_POST);
print_r($_FILES);
$new_song_name = $_POST["new_song_name"];
$new_song_artist = $_POST["new_song_artist"];
$song = $_FILES;
echo $new_song_name;
echo "<br />";
echo $new_song_artist;
echo "<br />";
print_r($song);
die();
}
但是回显变量只会显示为空数组,并且尝试从$ _POST访问变量时也会出现 undefined index 错误。
我应该通过$ http有什么特殊的方式发送音频文件吗?我真的觉得我缺少一些细节。
最佳答案
最后,我决定不使用angularjs $ http.post而是尝试使用$ .ajax来看看发生了什么,并且它确实有效!
这是我使用的:
$.ajax({
type : "post",
url : "uploads/songs",
data : fd,
cache : false,
contentType : false,
processData : false,
success: function() {
console.log("Hey");
}
});
关于javascript - AngularJS-如何通过$ http发布发送音频文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46556609/