好的,所以我试图弄清楚如何使用Parse.Files将图像保存到Parse,然后也可以稍后检索图像。现在,每当我加载页面时,都会自动创建一个新的Parse对象,但文件不正确。
我想要的是能够使用输入字段从文件中选择图像,在单击上传按钮后上传它,然后也可以稍后检索它,可能还有某种按钮。我不确定从哪里开始,所以任何帮助都值得赞赏!!!
我的按钮代码
<input type="file" class="imageFile" id="imageFile"/>
<input type="button" onclick="uploadImage()" class="uploadBtn" value="Upload Image" id="upload"/>
Javascript代码
<script type="text/javascript">
Parse.initialize("key", "key");
var GameScore = Parse.Object.extend("GameScore");
var gameScore = new GameScore();
function uploadImage() {
//var images = Parse.Object.extend("images");
var base64 = "V29ya2luZyBhdCBQYXJzZSBpcyBncmVhdCE=";
var file = new Parse.File("player1.png", { base64: base64 });
file.save({
success: function(file) {
alert('File saved, now saving product with file reference...');
// to fill the columns
gameScore.set("picture", file);
gameScore.save(null, {
success: function(gameScore) {
// Execute any logic that should take place after the object is saved.
gameScore.save();
alert('New object created with objectId: ' + gameScore.id);
},
error: function(error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});
},
error: function(error) {
alert('Failed to save file: ' + error.description);
}
});
}
</script>
答案 0 :(得分:1)
当我使用Parse作为Web应用程序时,这让我永远得到了。对我有用的是使用ajax。在下面的代码中,我们从输入元素中获取图像并将其存储在变量中。然后我们使用ajax(通过Parse的REST API)将图像发送到Parse。然后我们制作一个存储图像的新对象(表格)。然后我们创建一个包含我们可以访问图像的URL的单元格,然后我们创建另一个包含图像名称和网址的单元格,只是为了安全起见并有另一种方法来获取图片。
HTML:
<input type="file" class="imageFile" id="imageFile" accept="image/*">
JS:
/*Get image file given by user*/
var file;
var name;
$('#imageFile').bind("change", function (e) {
var files = e.target.files || e.dataTransfer.files;
// Our file var now holds the selected file
file = files[0];
name = file.name;
});
function uploadImage() {
if (file != null) {
var serverUrl = 'https://api.parse.com/1/files/' + file.name;
$.ajax({
type: "POST",
beforeSend: function (request) {
request.setRequestHeader("X-Parse-Application-Id", 'your app id');
request.setRequestHeader("X-Parse-REST-API-Key", 'your rest key');
request.setRequestHeader("Content-Type", file.type);
},
url: serverUrl,
data: file,
processData: false,
contentType: false,
success: function (data) {
var myimage = new Parse.Object("image_table"); //create new object
myimage.set({imageurl: data.url}); //set the url that will be used to retrieve the image
myimage.set({imagefile: {"name": data.name,"url": data.url,"__type": "File"}}); //save it's name and url in a json object for good measure
myimage.save(); //save and push the changes
},
error: function (data) {
var obj = jQuery.parseJSON(data);
alert(obj.error);
}
});
}
}