Django ajaxuploader 400 badrequest error - javascript

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.

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.

Link not sending back on a sharex custom uploader

I made a custom uploader on Glitch and it won't send the link back to Sharex (it gets saved on the server).
Here's the response part:
response.setHeader('Content-Type', 'application/json')
response.send(JSON.stringify({ success: true, file: { url: \`http://${process.env.PROJECT_DOMAIN}.glitch.me/i/${newFileName}\`, delete_url: \`http://${process.env.PROJECT_DOMAIN}.glitch.me/delete?filename=${newFileName}&key=${request.body.key}\`
I have tried this:
console.log(response.send(JSON.stringify({ success: true, file: { url: \`http://${process.env.PROJECT_DOMAIN}.glitch.me/i/${newFileName}\`, delete_url: \`http://${process.env.PROJECT_DOMAIN}.glitch.me/delete?filename=${newFileName}&key=${request.body.key}\`)
and got this:
{"success":true,"file":{"url":"http://block-is-a-virgin.glitch.me/i/Pztga80D.png","delete_url":"http://block-is-a-virgin.glitch.me/delete?filename=Pztga80D.png&key=goawayandleavemykeyalone"}}
Let me know if you need any more code to indentify the issue. Thanks.
Turned out it was a client side error.
The response thing wasn't set right and it didn't know how to grab out the url.

App Engine second upload to Blobstore not working

I have a form whose data is asynchronously uploaded to Blobstore. When the upload is completed, the backend page outputs another blobstore.get_upload_url() to use for a second upload.
However, when the second upload is performed, it gives a POST http://localhost:13080/_ah/upload/ah1kZXZ-YXZpc2JlcmdhbW8tMTQ2OTk2MTI5MTQ0OXIiCxIVX19CbG9iVXBsb2FkU2Vzc2lvbl9fGICAgICA_IoLDA 404 (Not Found) error
Here's the code (JS):
$.ajax({
url: upload_url,
data: formData,
contentType: false,
processData: false,
success: function (data) {
upload_url = data.url;
formData = new FormData();
},
async: true,
method: 'POST',
});
Here's the backend:
class InserisciDomandaHandler(blobstore_handlers.BlobstoreUploadHandler):
def post(self):
# ... uploads additional data to Datastore
self.response.headers['Content-Type'] = 'application/json'
obj = {
'url': blobstore.create_upload_url('/upload_photo'),
}
self.response.out.write(json.dumps(obj))
I checked the new url and it is different than the old one. Additionally, the new url seems valid.
Why does it give me a 404 error? Thanks
EDIT:
The url seems valid but, when used both in production and in local, it is not treated as valid by App Engine. So, although it "intuitively" makes sense, it doesn't make sense in practice.

reload page after processing javascript output in flask

I have a javascript snipped which uses ajax to send an email address to my flask views.py script. I want to send a message to that address if the email is not in my database or otherwise reload the website and show the user information for that email address. Here is my javascript code which sends the data to my views.py
<script type='text/javascript'>
$(".send_invite_message").click(function(evt) {
var Toemail = document.getElementById('To').value
$.ajax({
url: "/send_invitation_member",
type: "GET",
async: true,
cache: false,
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: { email: Toemail},
success: function(data) {
///do something
},
});
});
</script>
and in flask I would like to now have the option to send an email and if the email already exists in the database to reload the site
#app.route('/send_invitation_member', methods=['GET'])
def send_invitation_member():
if request.method == 'GET':
email = request.args.get('email')
search_result = check database for email entry
if search_result:
return render_template('show_members.html')
else:
send message and return json object
However the ajax script expects a json object back, so I don't know how to reload the site and show the user information. Is there any way to do this directly in flask or do I need to extend my javascript code and load the site from there?
thanks
carl
Since there's no way for an AJAX response to directly affect the page that's calling it, you'll need to extend your javascript a little (but only a bit).
In your success function, let's add the following:
success: function(data) {
if (data['url'] != null) document.location = data['url'];
else console.log('Got a valid JSON response, but no URL!');
}
This code will redirect the page to where the JSON specifies with its 'url' key. Now all that's left is to add it to our Flask code.
#app.route('/show_members')
def show_members():
return render_template('show_members.html')
#app.route('/somewhere_else')
def some_other_route():
return "It all works!"
#app.route('/send_invitation_member', methods=['GET'])
def send_invitation_member():
email = request.args.get('email')
search_result = check database for email entry
if search_result:
destination = url_for('.show_members')
else:
destination = url_for('.some_other_route')
send message and return json object
return Response(response=json.dumps({'url': destination}, mimetype='text/json')
I find when using flask it's better to separate your routes out into different functions depending on the HTTP method. And the url_for method? It's a life saver. You can find its docs here http://flask.pocoo.org/docs/0.10/api/#flask.url_for

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

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.

Categories

Resources