Uploading image to Parse using Javascript(CoffeeScript) and REST API - javascript

I'm trying to upload images to parse and later attach them to models, however whenever I upload one it returns as a successful upload but the url contains a broken image link.
for instance:
http://files.parse.com/aac0413c-eada-4602-9451-2ee5da7d1241/22eaa50b-1e61-4744-abf9-a57ba9f4123f-test.jpg
Here's the upload code:
getImg: ->
CameraHelper.fileUpload (file) =>
#file = file
forge.file.URL file, (url) =>
#fileURL = url
#$("#uploadImg").addClass("fadeIn").css("background-image", "url(#{url})")
#$("#removeImg").css("display", "inline")
, (content) ->
error "Error finding Image"
, ->
debug "Upload Cancelled"
serverUrl = 'https://api.parse.com/1/files/test.jpg'
parseFile = _.extend #file,
type: "image/jpeg"
name: "share.jpg"
$.ajax
type: "POST",
beforeSend: (request)->
request.setRequestHeader "X-Parse-Application-Id", 'MY-APP-ID'
request.setRequestHeader "X-Parse-REST-API-Key", 'MY-REST-API-ID'
request.setRequestHeader "Content-Type", "image/jpeg"
url: serverUrl
data: parseFile
processData: false
contentType: false
success: (data) ->
alert "File available at: " + data.url
error: (data) ->
obj = jQuery.parseJSON(data)
alert obj
CameraHelper =
fileUpload: (success, err) ->
if APP
forge.file.getImage
saveLocation: "file"
source: "camera"
height: "620px"
width: "620px"
, (file) ->
debug "Successfully uploaded img"
success?(file)
, (content) ->
error "Error in uploading img", content
err?()
else
debug "Sorry that feature is not currently available on the mobile web."
CameraHelper
NOTE: I'm using triggerIO, also referenced: https://www.parse.com/questions/uploading-files-to-parse-using-javascript-and-the-rest-api to no avail
parseFile is the image I'm trying to upload

I'm not sure exactly what Parse are expecting in the POST body, but I think they want the entire body to be the image data, with no multi-part encoding.
That means you need to do two things:
Firstly, when uploading files, you should use the files parameter, rather than data. See https://trigger.io/docs/current/api/modules/request.html#forgerequestajaxoptions. This is true whenever you're uploading files, not just with Parse.
Secondly, as I think Parse don't want an encoded POST body, use the fileUploadMethod: "raw" parameter to just dump the image data directly into the request.

Related

Sending image from flask to javascript

I am trying to send an image from the flask server to the web script. The first server connects to another API and gets an image. I don't want to save this image just forward it to the web application script.
#app.route('/api/image', methods=['GET'])
def return_image():
r = requests.get(f"{api_url}/image")
return send_file(
BytesIO(r.content),
mimetype='image/jpeg',
as_attachment=True,
attachment_filename='test.jpg')
I am trying to get this image by ajax request and display it.
function updateImage() {
$.ajax({
url: "/api/image",
type: "GET",
dataType: 'image/jpg',
success: function (res) {
$(theImg).attr("src", 'data:image/png;base64,'+ res);
M.toast({
html: 'Loading image: Success'
})
},
error: function () {
M.toast({
html: 'Loading image: Fail'
})
}
});
}
I tried to make this work but wasn't able to. I really appreciate your help.
At a glance your JS writes a data-uri to the src attribute, but res is actually the binary data with a image/png mimetype.
So you either need to base64 encode r.content on the server side, here's an example which actually creates the entire uri server side, then return that string and have your JS add that to the src attribute.
Or if you just want make your JS support the exisitng endpoint you could probably create a blob based on /api/image response, then write that to the img tag.

Upload a javascript generated PDF file to server

Please note I am uploading a file generated at runtime, NOT a user submitted file. This is where my problem lies, taking that file and sending it along has proven itself to be truly a challenge.
I'm using PDFMake to generate a pdf file. It took me A LONG time to get this code working, tl;dr of it is I convert the pdf doc info to a buffer, make a new File object with that buffer, attach that file object to a formdata object, and send it to my server.
Here is the code:
var pdfGen = pdfMake.createPdf(docDef);
pdfGen.getBuffer(function(buffer){
var pdf = new File(buffer, "testpdf.pdf", {type: "application/pdf"});
var data = new FormData();
data.append('upload', pdf);
data.append('content-type', 'application/pdf');
$.ajax({
method: "POST",
url: "/index.cfm?action=admin:service.upload_pdf",
data: data,
processData: false,
contentType: false,
success: function(msg){
console.log(msg);
},
error: function(msg){
console.log(msg);
}
})
})
The problem is that the file I get on my server isn't a valid PDF. The application type is listed as application/octet-stream. The function I'm pushing the File object to SHOULD be rejecting everything except pdf's, so I'm not sure where the error is exactly.
I've been at this for two days now and I'm at a loss so any help is GREATLY appreciated.
Have you tried converting your generated PDF into Base64 and then sending the result to your server?
Here's what I mean:
var pdfGen = pdfMake.createPdf(docDef);
pdfGen.getBase64((data) => {
PostToServer(data);
});
Source: https://github.com/bpampuch/pdfmake

Send binary of file from ajax to ashx file as application/octet-stream

I need to send with ajax a file Binary to .ashx file (c# .net environment).
When I send it, the "Request Payload" must be of Content-Type: "application/octet-stream", this is the requirement from the server side. My problem is When I run my script, It sends the file as a normal type instead of "application/octet-stream". if the file is jpg, then it sends it as Content-type: "image/jpeg", This is not good for me. I wanna send the file in Binary format.
right now what I have is this:
var formData = new FormData();
formData.append('file',file);
$.ajax({
url: gatewayUrl,
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(data){},
error: function(){}
});
I read about FileReader, and about File.getAsBinary() but non of them is working for me. I am struggling with the ArrayBuffer and I'm not sure if I'm on the right direction..
This is the direction I'm thinking about but I can't figure out if that's the correct way to go with or not:
function get_file_binary(file){
var fileReader = new FileReader();
fileReader.readAsArrayBuffer(file);
fileReader.onload = function(e){
var res = fileReader.result;
var res2 = new Int8Array(res);
return res2;
}
}
But when I try this I get "undefined" at the "Request Payload" on chrome.

Download Binary data file from java script

Hi Here my Sql Table
I want to download those files using java script . I get Record from "ID" to my java script . I want to download those files, how can i do that
here is the my script get file by ID
function DownloadFile(e) {
$.ajax({
dataType: 'JSON',
url: '/api/FileAttachment/GetFileByID',
async: false,
data: { id: e },
success: function (data) {
downloadPDFfile(data);
}
});
}
function downloadPDFfile(a) {
// I want write download code here
}
If you want to download a file from server, at first create a url request like this:
function downloadPDFfile(param) {
var downloadUrl = http://www.yourhost.com/download?id=param
window.open(downloadUrl);
}
At your server, write code to receive this request, get requested param(s), read your binary data from db then response this data to client as a stream and the browser will do it's job.
Dont't forget to specify HTTP response header fields. For example:
Content-Type: text/html /* MIME type */
Content-Disposition: attachment; filename="fname.ext" /* Using 'attachment' option to raise a "File Download" dialogue box */

Django ajaxuploader 400 badrequest error

Submitted.html
The JS is also surrounded by a document.ready function
var uploader = new qq.FileUploader({
action: "{% url 'QCOMLTE:imager' %}",
element: $('#file-uploader')[0],
multiple: true,
onComplete: function(id, fileName, responseJSON) {
if(responseJSON.success) {
alert("success!");
} else {
alert("upload failed!");
}
},
onAllComplete: function(uploads) {
// uploads is an array of maps
// the maps look like this: {file: FileObject, response: JSONServerResponse}
alert("All complete!");
},
params: {
'csrf_token': "{{ csrf_token }}",
'csrf_name': 'csrfmiddlewaretoken',
'csrf_xname': 'X-CSRFToken'
}
});
elsewhere in the html body
<div id="file-uploader">
<noscript>
<p>Please enable JavaScript to use file uploader.</p>
</noscript>
</div>
urls.py
urlpatterns = patterns('',
url(r"^Submitted/$", views.HybridDetailView.as_view(), name='Submitted'),
url(r'^(?P<object_type>\w+)/process/$', views.process, name='process'),
url(r'^(?P<object_type>\w+)/$', views.generic_view, name='generic'),
url("$^", views.head, name='head'),
url("uploader", views.upload, name= 'imager'),
)
views.py
#AjaxFileUploader
def upload(request):
response = {'files': []}
script_dir = os.path.dirname(__file__)
# Loop through our files in the files list uploaded
print('request',request)
print(request.FILES)
for item in request.FILES.getlist('files[]'):
file = UploadedFile(item)
with open(script_dir + '/Excel/' + file.name) as destination:
for chunk in file.chunks():
destination.write(chunk)
response['files'].append(file)
print('appended')
return HttpResponse(json.dumps(response), content_type='application/json')
also contains 'ajaxuploader' in the installed apps list
When I try to submit a file through the button it sends the post call but receives a 400 (BAD REQUEST) Error.
It's not even reaching the python from what I can tell, at least not the view code. It seems to form the request URL correctly
http://localhost:8000/QCOMLTE/uploader?qqfile=powered_by.png
And when you go to the URL it sends a message stating that post calls are only allowed.
This is similar to Default django-ajax-uploader with s3 backend gives MalformedXML error
Except that I'm not using any backends, just trying to grab the file/s and save them to a directory.
UPDATE 8/25/14:
Removed the decorator from the view. This results in the error not being sent. After printing the request it becomes evident that the file is being sent to the GET path instead of the FILE path. I don't know how to change this.
After finding this Need a minimal Django file upload example
I preceded to try and imitate it, to find that the FILE and POST requests were actually going through, unlike the ajax/jquery I was using. The JQuery was
$('#uploadform').submit(function (e){
console.log('submitting')
var data = new FormData($('#uploadform').get(0));
$.ajax({
type: 'POST',
url: "{% url 'QCOMLTE:imager' %}",
data: data,
success: function(data){console.log(data)},
error: function(data){console.log(data)},
cache: false,
processData: false,
contentType: false
});
e.preventDefault()
});
except the type was below URL.
I tried changing it to a $.post request and it was trying to post to the wrong URL then...
So I decided to change it back, and this time put type at the top of the ajax call. It then worked... and still does after much testing.

Categories

Resources