Can't view uploaded PDF file in data browser - javascript

I uploaded a pdf file to parse and it is visible in the data browser, but when I try to view it it says failed to load. I believe that my upload code is correct because it works for .docx files but not .pdf. Any ideas? Here is my code
function uploadFile (uploadId,fileName){
var fileUploadControl = $("#fileUpload")[0];
if(fileUploadControl.files.length>0){
var file = fileUploadControl.files[0];
var parseFile = new Parse.File(fileName,file);
parseFile.save().then(function(){
console.log("nsucciess");
//file has been saved to parse
},function(error){
//file could not be read or saved
console.log("error");
});
//var currentUser = Parse.User.current();
//currentUser.set(fileName,parseFile);
var ProjectFile = Parse.Object.extend("ProjectFile");
var projectFile = new ProjectFile();
projectFile.set("file",parseFile);
projectFile.save(null,{
success:function(projectFile){
console.log("success");
}
});
alert("everything works");
}
else{
alert("oh no");
}
}

Just solved: you have to add https://docs.google.com/viewer?url= before the link provided by Parse.com. For example: var yourUploadedPdfLink = "http://files.parsetfss.com/56accfec-1956-xxxxxx-abe8-xxxxxx/tfss-a7076e9c-xxxx-45fe-a8e8-xxxxxxx-MYDOCUMENT.pdf" To read it: "https://docs.google.com/viewer?url=" + yourUploadedPdfLink
And it'll works. So, you can't read pdf files clicking on them from Parse.com dashboard (at the moment).

Related

Flask-wtf with trix-editor - How do I upload images

I'm using Flask with one of my wtforms TextAreaFields mapped to Trix-Editor. All works well except for images using the built toolbar attach button.
I'd like to save the images to a directory on the backend and have a link to it in the trix-editor text. I'm saving this to a database.
I can make this work by adding an <input type='file'/>in my template like so:
{{ form.description }}
<trix-editor input="description"></trix-editor>
<input type="file"/>
and the following javascript which I found somewhere as an example.
document.addEventListener('DOMContentLoaded', ()=> {
let contentEl = document.querySelector('[name="description"]');
let editorEl = document.querySelector('trix-editor');
document.querySelector('input[type=file]').addEventListener('change', ({ target })=> {
let reader = new FileReader();
reader.addEventListener('load', ()=> {
let image = document.createElement('img');
image.src = reader.result;
let tmp = document.createElement('div');
tmp.appendChild(image);
editorEl.editor.insertHTML(tmp.innerHTML);
target.value = '';
}, false);
reader.readAsDataURL(target.files[0]);
});
// document.querySelector('[role="dump"]').addEventListener('click', ()=> {
// document.querySelector('textarea').value = contentEl.value;
// });
});
This saves the image embedded in the text. I don't want that because large images will take up a lot of space in the database and slow down loading of the editor when I load this data back into it from the database.
It is also ugly having the extra button when Trix has an attachment button in it's toolbar. So, I'd like to be able to click the toolbar button and have it upload or if that is too hard, have the built in toolbar button save the image embedded.
To save the images to a folder instead of embedded, the Trix-editor website says to use this javascript https://trix-editor.org/js/attachments.js
In this javascript I have to provide a HOST so I use
var HOST = "http://localhost:5000/upload/"
and I set up a route in my flask file:
#tickets.post('/_upload/')
def upload():
path = current_app.config['UPLOAD_DIRECTORY']
if request.method == 'POST':
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
if file.filename == '':
flash('No selected file')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
session["id"] = filename
file.save(os.path.join(path, filename))
return send_from_directory(path, filename)
I can select an image and it shows in the editor and it uploads to the directory on my backend as expected. But when I save the form the location of the image is not in in the document text (should be in there as something like <img src="uploads/image.png>
On the python console I see
"POST /_upload/ HTTP/1.1" 404 -
I can make this go away if I change the return on my route to something like return "200" But all the examples I have seen about uploading files have this or a render_template. I don't want to render a template so I'm using this although I don't really understand what it does.
I'm assuming I need to return something the javasript can use to embed the image link in the document. But I'm a total newbie (like you didn't figure that out already) so I don't know what to do for the return statement (assuming this is where the problem lies).
If anyone else is trying to figure this out this is what I ended up doing.
Still needs a but of tweaking but works.
First I modified the example javascript for uploading to use Fetch instead of XMLHttpRequest
const editor = document.querySelector('trix-editor');
(function() {
HOST = '/_upload/'
addEventListener("trix-attachment-add", function(event) {
if (event.attachment.file) {
uploadFileAttachment(event.attachment)
}
// get rid of the progress bar as Fetch does not support progress yet
// this code originally used XMLHttpRequest instead of Fetch
event.attachment.setUploadProgress(100)
})
function uploadFileAttachment(attachment) {
uploadFile(attachment.file, setAttributes)
function setAttributes(attributes) {
attachment.setAttributes(attributes)
alert(attributes)
}
}
function uploadFile(file, successCallback) {
var key = createStorageKey(file)
var formData = createFormData(key, file)
fetch(HOST, {method: 'POST', body: formData}).then(function(response){
response.json().then(function(data){
alert(data.file, data.status)
if (data.status == 204) {
var attributes = {
url: HOST + key,
href: HOST + key + "?content-disposition=attachment"
}
console.log(attributes)
successCallback(attributes)
}
})
})
}
function createStorageKey(file) {
var date = new Date()
var day = date.toISOString().slice(0,10)
var name = date.getTime() + "-" + file.name
return [day, name ].join("/")
}
function createFormData(key, file) {
var data = new FormData()
data.append("key", key)
data.append("Content-Type", file.type)
data.append("file", file)
return data
}
})();
Then modified my Flask route (which I'll refactor, this was just slapped together to make it work):
def upload():
path = current_app.config['UPLOAD_DIRECTORY']
new_path = request.form["key"].split('/')[0]
file_upload_name = os.path.join(path, request.form["key"])
print(file_upload_name)
upload_path = os.path.join(path, new_path)
if request.method == 'POST':
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
if file.filename == '':
flash('No selected file')
return redirect(request.url)
if file and allowed_file(file.filename):
if not os.path.exists(upload_path):
os.mkdir(upload_path)
filename = secure_filename(file.filename)
session["id"] = filename
attachment = os.path.join(upload_path, filename)
file.save(attachment)
file.close()
os.rename(attachment, file_upload_name)
print(os.listdir(upload_path))
return jsonify({'file': attachment, 'status': 204})
return f'Nothing to see here'
Anyway, I hope that helps as it took me ages to figure out.

How to implement csv or excel file upload in spring boot and jsp using ajax?

I am new to Spring Boot, and I am trying to implement a csv or excel file upload in my application. I have created a button in JSP page to upload file and store in my database. To upload file from backend, I have created API and after testing API, it is working fine. But the code written inside the script is not working properly. I have written the below code:
Each time when I am trying to upload my file, I am getting 404 error. I do not know why. Any suggestions would be appreciated.
function uploadpindata(){
var delivercityid = document.getElementById('cityid').value;
var formData = new FormData();
var fileSelect = document.getElementById("file");
if(fileSelect.files && fileSelect.files.length == 1) {
var file = fileSelect.files[0];
formData.set("file",file,file.name);
console.log("Got the file");
}else{
$("#file").focus();
return false;
}
var request = new XMLHttpRequest();
try {
request.onreadystatechange=function() {
if(request.readyState==4) {
var v = JSON.parse(request.responseText);
if(v.status==="OK") {
alert("New File Uploaded successfully");
location.reload();
}
}
}
request.open('POST',"../<%=AkApiUrl.uploadpincodedata%>/"+delivercityid);
request.send(formData);
} catch(e) {
swal("Unable to connect to server","","error");
}

selecting a file using location url instead of input file in html5 filereader for javascript

i want to give the file location url for the code to get my file instead of using input file in html part , to pass the file to the code
the code pasted below works if i use " input type= "file" " to get the file, but if i use url (like below) it gives a error
fileInput1.addEventListener is not a function
at window.onload
here is the code
window.onload = function() {
var z ="C:/Users/akash/Desktop/riidl/UTham.txt"
var fileInput1 = z;
if (fileInput1){
fileInput1.addEventListener('change', function(e) {
var file = fileInput1.files[0];
var textType = /text.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(e) {
spamdata=reader.result;
document.getElementById('here').onclick = console.log(spamdata);
}
reader.readAsText(file);
}
});
}
}
Accessing local files is not allowed in JavaScript for security purposes.
Pl refer to this answer for more details.
https://stackoverflow.com/a/372333/3626796

On Bootstrap modal confirm button click ,create and download file jquery or knockout js

I have a bootstrap modal( bootbox ), on which confirm action, i want to create a file which contains some numbers and download the file as a text file.
I have already referred Create a file in memory for user to download, not through server but its not helpful in my case.
Here is the code :
bootbox.confirm("Item not found! Do you want to download the text file?", (yes) => {
var items = response.itemNumbers;
this.href = "data:text/plain;charset=UTF-8," + encodeURIComponent(items);
});
I have tried this as well :
bootbox.confirm("item not found! Do you want to download the text file?", (yes) => {
var itemNumbers = response.itemNumbers;
var textFile = null;
var data = new Blob([itemNumbers], { type: 'text/plain' });
// deleting old text file
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
var link = $(textFile).attr("href");
document.location.href = link;
});
EDIT : When I run this, first code runs and nothing happens. Second gives error about Blob conversion : Syntax error, unrecognized expression: blob:http%3A//localhost%3A51876/028f2122-1646-4b2e-ae2c-2a1b588fdd8d
Got it! thanks #kb. for helping. The link you provided had the answer. Just posting here for future visitors: below code would create a file which contains "abcd,wxyz" and prompt for download :
var items = "abcd,wxyz";
var json = JSON.stringify(items);
var blob = new Blob([json], {type: "octet/stream"});
var url = window.URL.createObjectURL(blob);
window.location.assign(url);
reference : JavaScript blob filename without link

filepicker.io bombing out on upload to S3 in Meteor app

I am working on a file uploader for my app and I settled on Filepicker.io. Everything is working fine except for one thing..When I upload an image to S3 I can only upload the URL that Filepicker returns (not the image itself).
The below is successful, but
Template.new_aphorism.events({
'change #attachment': function(event){
var savedFile = JSON.stringify(event.fpfile);
var parsedJSON = eval('('+savedFile+')');
var url=parsedJSON.url;
$('input[name=new_aphorism_image]').val(url);
console.log("saved file is:" + savedFile);
console.log(url);
filepicker.store(url, {location: 'S3'}, function(fpfile){
output.html('Uploaded: '+fpfile.filename+'');
}, function(fperror){
output.text(fperror.toString());
}, function(progress){
output.text("Uploading... ("+progress+"%)");
});
}
});
I get back as my message:
File stored in S3 at VnAa2YsOS6wOECNMWpwn_temp.txt and available at https://www.filepicker.io/api/file/vVtWTOl7QqOJ7gPmXkHQ
I have tried passing this and event.fpfile into my filepicker.store function but it just doesn't work.
Solved.
In the same function:
var file = event.fpfile;
filepicker.store(file, {location: 'S3'}, function(fpfile){

Categories