Uploading an image file to GAE datastore - google-app-engine

Im trying to upload an image file to the GAE datastore using jQuery within CoffeScript.
The upload jQuery Post function I'm using is:
$.post "/uploadBTS?bts_spriteSheet=#{#bts_spritesheet_url}", (data) =>
console.log 'succsess'
#bts_spritesheet_url is obtained from the html5 File Api:
handleSpritesheetSelection = (evt) =>
files = evt.target.files
f = files[0]
reader = new FileReader()
# Closure to capture the file information.
reader.onload = ((theFile) =>
return (e) =>
#bts_spritesheet_url = e.target
)(f)
reader.readAsDataURL(f)
document.getElementById('upload_spritesheet').addEventListener('change', handleSpritesheetSelection, false)
The handeler in GAE for a post call to /uploadBTS is:
class UploadBTS(webapp2.RequestHandler):
def post(self):
# get information from form post upload
bts_spriteSheet = self.request.get('bts_spriteSheet')
# create database entry for uploaded image
bts_entry = Building_Tile_Sets()
bts_entry.image = db.Blob(bts_spriteSheet)
bts_entry.put()
and lastly the database I'm trying to put the information is a define thus:
# Database containg the bts
class Building_Tile_Sets(db.Model):
image = db.BlobProperty(default=None)
I get the following error when trying the upload:
POST http://localhost:8080/uploadBTS?bts_spriteSheet=[object%20FileReader]&bts_jason=[object%20Object]&bts_name=one 500 (OK)
Can anyone see where I'm going wrong?

Related

Video Streaming: Using Blob URL, -Video Seek casting 404 file not found

I am a developer/creator of a Video Streaming Service, in order to server the movies I am using
createObjectURL() (BLOB URL).
The Blob Url is created and served to the html5 video element
after the video is rendered the blob URL is revoked in order to prevent the user from accessing the private movie file, however is result of this when I try to seek through the video I get an error file not found.
Would i need to recreate the blob every time I seek the video or am I declaring my blob wrong?
async renderBlob(url){
const myPlayer = this.player.current;
var xhr = new XMLHttpRequest();
xhr.open('GET', 'movie.mp4', true);
xhr.responseType = 'blob';
xhr.onload = () => {
this.setState({src: URL.createObjectURL(xhr.response)})
myPlayer.src = this.state.src
myPlayer.play()
};
xhr.onerror = function(e) {
alert("Error " + e.target.status + " occurred while receiving the document.");
};
xhr.send();
}
after the video is playing:
URL.revokeObjectURL(this.state.src)
Short videos SEEK okay where as Longer Videos 1) to longer to load and 2 do not seek
GET blob:http://localhost:3000/e5fd2c07-3f8a-407e-815f-7b9314d9156d net::ERR_FILE_NOT_FOUND

Flutter Monitor FileUpload progress using the http package

I have been using the following code to upload files on my server as it is doing the job but i want to monitor the Upload Progress Percentage during the opration and Update the UI accordingly to reflect the prgress to the user
uploadFile({File imageFile, String refCode}) async {
// open a bytestream
var stream =
new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
// get file length
var length = await imageFile.length();
// string to uri
var uri = Uri.parse(
'http://-------------/api/FilesUploadB/?refCode=$refCode');
// create multipart request
var request = new http.MultipartRequest("POST", uri);
// multipart that takes file
var multipartFile = new http.MultipartFile('file', stream, length,
filename: basename(imageFile.path));
// add file to multipart
request.files.add(multipartFile);
// send
var response = await request.send();
// listen for response
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
//return response.
}
NOTE that the value in the listen is getting me the final return from the WebAPI on the server.
how to achieve that?
Take a look at this example on GitHub. It demonstrates how you can access the current upload progress of your file.

Django throws {"non_field_errors":["Invalid data. Expected a dictionary, but got tuple."]} React JS

Trying to send file via fetch post from react to django rest,but got this django response shows:
{"non_field_errors":["Invalid data. Expected a dictionary, but got tuple."]}
I am trying to send pdf generated file to django but unable to do, first I create pdf then send via fetch post request
ReactJS
genPDF=(evt)=>{
evt.preventDefault();
html2canvas(document.getElementById("pdfid")).then(canvas=>{
let img=canvas.toDataURL('img/png');
let doc=new JsPDF();
doc.addImage(img,'JPEG',30,30);
doc.output('blob');
//doc.save('test.pdf');
let formdata=new FormData();
formdata.append('file',doc);
fetch(`http://127.0.0.1:8000/chauffeur/pdf_upload/`,
{
method: 'POST',
body:formdata,
}
).then(response => response.json()).catch(error => console.error('Error:', error));
//this.postpdf(formdata)
});
};
DJANGO
class PdfUpload(APIView):
parser_classes = (MultiPartParser, FormParser,)
def get(self, request):
return Response([PdfSerializer(file).data for file in Pdf.objects.all()])
def post(self,request):
payload=(request.data,request.FILES)
serializer=PdfSerializer(data=payload)
if serializer.is_valid():
serializer.save()
return Response("File Saved in Backend",status=status.HTTP_201_CREATED)
return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)
SERIALIZER.PY
class PdfSerializer(serializers.ModelSerializer):
class Meta:
model = Pdf
fields = ['file',]
Am I send the a correct file because it PDF generated and then afterwards I send it through fetch request or It may be problem in formdata as at the django end it is expecting dictionary but formdata acting as tuple?
Try this:
formdata.append({'file':doc});
Instead of
formdata.append('file',doc);

How to upload audio file to Firebase Storage?

I'm trying to upload audio file to Firebase Storage in my Ionic2 project.
First I recorded a audio file using Media plugin (Cordova plugin), and this file is playing well. From the Android storage and from the media plugin method (this.media.play()...;).
Second I need to push the recorded file to Firebase Storage.
this is my code:
let storageRef = firebase.storage().ref();
let metadata = {
contentType: 'audio/mp3',
};
let filePath = `${this.file.externalDataDirectory}`+`${this.fileName}`;
const voiceRef = storageRef.child(`voices/${this.fileName}`);
var blob = new Blob([filePath], {type: 'audio/mp3'});
voiceRef.put(blob);
After reading the Firebase doc, I can push blob to Firebase.
The file is successfully pushed to Firebase Storage with empty data (95 Byte).
this is screenshot:
The problem isn't a Firebase issue
My problem is solved by using the File cordova plugin method (readAsDataURL()) and the putString(fileBase64,firebase.storage.StringFormat.DATA_URL) method.
First, I create a file reference:
let filePath = "this.file.externalDataDirectory" + "this.fileName";
Then I transform the file to a base64 string by using the readAsDataURL method that returns a promise containing the file as a string base64. Also, I push the file to Firebase using the putString method that has two parameters the File that returned by the readAsDataURL and the second is firebase.storage.StringFormat.DATA_URL.
My Final code:
let storageRef = firebase.storage().ref();
let metadata = {
contentType: 'audio/mp3',
};
let filePath = `${this.file.externalDataDirectory}` + `${this.fileName}`;
this.file.readAsDataURL(this.file.externalDataDirectory, this.fileName).then((file) => {
let voiceRef = storageRef.child(`voices/${this.fileName}`).putString(file, firebase.storage.StringFormat.DATA_URL);
voiceRef.on(firebase.storage.TaskEvent.STATE_CHANGED, (snapshot) => {
console.log("uploading");
}, (e) => {
reject(e);
console.log(JSON.stringify(e, null, 2));
}, () => {
var downloadURL = voiceRef.snapshot.downloadURL;
resolve(downloadURL);
});
});
That's working fine for me.
Thanks.

how can i get the local image url to store in firebase

I have to store user profile photo in my firebase data base. I want to store a local image that has this path : "www/img/avatar.jpeg". I try this code to get image url
$scope.user.image="data:img/avatar.jpeg;base64"
But when running my code i get this message error : ERR_UNKNOWN_URL_SCHEME.
The user will have to select the photo, so you need a file selector in your HTML:
<input type="file" id="file" name="file" />
Then you can handle it in JavaScript with:
function handleFileSelect(e) {
var file = e.target.files[0];
// Get a reference to the location where we'll store our photos
var storageRef = storage.ref().child('chat_photos');
// Get a reference to store file at photos/<FILENAME>.jpg
var photoRef = storageRef.child(file.name);
// Upload file to Firebase Storage
var uploadTask = photoRef.put(file);
uploadTask.on('state_changed', null, null, function() {
// When the image has successfully uploaded, we get its download URL
var downloadUrl = uploadTask.snapshot.downloadURL;
// Set the download URL to the message box, so that the user can send it to the database
textInput.value = downloadUrl;
});
}
file.addEventListener('change', handleFileSelect, false);
This code comes from the Zero To App talk at Google I/O. Complete code is available in this gist.
Where it adds the download URL to a text box, you'll want to save it in the database.

Resources