我们正在尝试创建一个文件上传系统。我们目前在upload.ejs中有一个表单,允许用户选择一个文件,然后表单调用upload.js,它使用Parse的REST API上传文件。在REST API的成功字段中,我们保存有关上载到我们的解析数据库的文件的信息。我们还想保存有关用户上传文件的信息,但Parse.User.current()返回null。 我们的upload.js保存在公共文件夹中,代码如下:
$(function() {
var file;
$('#fileselect').bind("change", function(e) {
var files = e.target.files || e.dataTransfer.files;
// Our file var now holds the selected file
file = files[0];
});
$('#uploadbutton').click(function() {
var serverUrl = 'https://api.parse.com/1/files/' + file.name;
$.ajax({
type: "POST",
beforeSend: function(request) {
request.setRequestHeader("X-Parse-Application-Id", 'YOUR-APPLICATION-ID');
request.setRequestHeader("X-Parse-REST-API-Key", 'YOUR-REST-API-KEY');
request.setRequestHeader("Content-Type", file.type);
},
url: serverUrl,
data: file,
processData: false,
contentType: false,
success: function(data) {
//alert("File available at: " + data.url);
var Note = Parse.Object.extend("Note");
var note = new Note();
note.set("File Name", file.name); //change to user inputted file name
note.set("url", data.url);
//note.set("uploader", Parse.User.current());
console.log(Parse.User.current());
note.save();
var success = "<p>File Successfully Added. View it by clicking <a target='_blank' href="+data.url+">Here</a></p>";
$("#uploadMessage").addClass("uploadPadding");
$('#uploadMessage').append(success);
//TO DO: redirect off page
},
error: function(data) {
var obj = jQuery.parseJSON(data);
alert(obj.error);
}
});
});
});