How to add an uploaded file to a list of already uploaded files in Vue? - file-upload

I currently have a file uploader that accepts a single CSV file. Then with axios I POST such file to the server and everything works just fine. What I'm not being able to achieve is being able to upload another CSV that will get added to the list of CSVs uploaded. I'm not talking about uploading various files at once, I'm taking about uploading different files at different points in time.
This is the method that is used to select a CSV file in the .vue file.
staticCampaignCSVSelected: function (file) {
console.log('campaign-detail.vue#staticCampaignCSVSelected', file)
let vc = this
vc.selectedHeuristicId = -1
Campaign.uploadStaticCSV(vc.campaign, file[0])
.then(
function (data) {
alert('CSV cargado con exito')
}
)
.catch(
function (err, data) {
console.log("campaign-detail#staticCampaignCSVSelected - catch", err.response)
alert(err.response.data.error)
}
)
},
This is the function that I have in some other JS file to POST to the API:
function uploadStaticCSV (campaign, csv) {
console.log('Campaign#uploadStaticCSV', campaign, csv)
//long list of assertions
let formData = new FormData()
formData.append('csv', csv)
return axios.post(API.campaignUploadStaticCSV(campaign.id), formData)
}
And this is the function I have in my endpoints.js file:
campaignUploadStaticCSV: function (id) { return this.campaign(id) + '' + '/csv' },
I haven't found a way to properly pass a[file] array as a parameter to the functions, which is what I believe I need to somehow do.
Any help would be appreciated :)

As far as i understood your question you need a way to pass a file from browser interface to your staticCampaignCSVSelected(file) method. If so why not to use an input model or a simple event or a watcher. E.g.
<input type="file" #input="staticCampaignCSVSelected($event.target.files[0])" />
But also i see a mistake in your code. You should append .then().catch() callbacks to axios.post() itself but not to Campaign.uploadStaticCSV() method.
And
return axios.post()
will not return a server response. You have to handle it in
axios.post().then(response => {})
callback

Related

Adobe PDF Embed API Save Content To Base64

Using Adobe PDF Embed API, you can register a callback:
this.adobeDCView = new window.AdobeDC.View(config);
this.adobeDCView.registerCallback(
window.AdobeDC.View.Enum.CallbackType.SAVE_API, (metaData, content, options) => {
})
Content is according to the docs here: https://www.adobe.io/apis/documentcloud/dcsdk/docs.html?view=view
content: The ArrayBuffer of file content
When I debug this content using chrome inspector, it shows me that content is a Int8Array.
Normally when we upload a pdf file, the user selects a file and we read as dataURI and get base64 and push that to AWS. So I need to convert this PDF's data (Int8Array) to Base64, so I can also push it to AWS.
Everything I have found online uses UInt8Array to base64, and I don't understand how to go from Int8Array to UInt8Array. I would think you can just add 128 to the signed int to get a ratio between 0-256, but this doesn't seem to work.
I have tried using this:
let decoder = new TextDecoder('utf8');
let b64 = btoa(decoder.decode(content));
console.log(b64);
But I get this error:
ERROR DOMException: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.
Please help me figure out how to go from Int8Array to Base64.
I use the function in this answer.
For Embed API, use the "content" parameter from the save callback as the input to the function.
You can see a working example at this CodePen. The functional part is below.
adobeDCView.registerCallback(
AdobeDC.View.Enum.CallbackType.SAVE_API,
function (metaData, content, options) {
/* Add your custom save implementation here...and based on that resolve or reject response in given format */
var base64PDF = arrayBufferToBase64(content);
var fileURL = "data:application/pdf;base64," + base64PDF;
$("#submitButton").attr("href", fileURL);
/* End save code */
return new Promise((resolve, reject) => {
resolve({
code: AdobeDC.View.Enum.ApiResponseCode.SUCCESS,
data: {
/* Updated file metadata after successful save operation */
metaData: { fileName: urlToPDF.split("/").slice(-1)[0] }
}
});
});
},
saveOptions
);

How can I create a JavaScript global variable?

This is the part of my .html file, where I use an xmlhttp request, and then try to access the JSON object outside of a function.
''''
<html>
<head>
<title>make_activities_table.html</title>
</head>
<body>
<script>
var act_obj_array;
// Get file activities.json and create JSON object
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if ( this.readyState == 4 && this.status == 200 ) {
act_obj_array = JSON.parse( this.responseText);
}
console.log(this.responseText);
console.log('Inside function = ' + act_obj_array);
};
xmlhttp.open( "GET", "activities.json", true);
xmlhttp.send();
console.log( 'Outside function = ' + act_obj_array);
</script>
</body>
''''
I'm trying to access the JSON object 'act_obj_array' outside of the xmlhttp.onreadystatechange function. From what I read, in JavaScript, to make a variable global, you define it outside of any function, which, clearly I have done here. But when I console.log 'act_obj_array, outside the function, I get undefined.
activities.json, is a file, that exist in the same directory of my web hosting's server. It is a JSON formatted file. I can see the information in the file quite clearly when I console.log( this.responseText );
What do I need to do to create a JSON object from an xmlhttp request, and then be able to access the JSON object from the rest of my code?
Well, since no one wanted to answer, I came up with a solution, and, I want to work on a second solution.
The solution I have now, I added a function after the line, inside a function:
act_obj_array = JSON.parse( this.responseText);
which is a function, that builds my table from my JSON object. At first, I just added the script in the body of the document, but, then, I defined the function in an external JavaScript sheet. This looked much cleaner.
The other solution, and one I haven't played with yet, is to use the 'fetch' method to read in my JSON file. That way, I may not have to use a function to create my JSON object.

How to download file from Sanity via HTTP?

I would like to know if there is possibility to download file from Sanity with HTTP request?
I only have reference ID:
{
file: {
asset: {
_ref: "file-fxxxxxxxxxxxxxxxxxxxx-xlsx"
_type: "reference"
}
}
}
I would like to do this is this scenario:
<a href="https://cdn.sanity.io/assets/clientID/dataset/file-xxxxxxxxxxx-xlsx">
Download File
</a>
You can, indeed 🎉 With a bit of custom code you can do it just from the _ref, which is the file document's _id
Creating the URL from the _ref/_id of the file
The _ref/_id structure is something like this: file-{ID}-{EXTENSION} (example: file-207fd9951e759130053d37cf0a558ffe84ddd1c9-mp3).
With this, you can generate the downloadable URL, which has the following structure: https://cdn.sanity.io/files/{PROJECT_ID}/{DATASET}/{ID_OF_FILE}.{EXTENSION}. Here's some pseudo Javascript code for the operation:
const getUrlFromId = ref => {
// Example ref: file-207fd9951e759130053d37cf0a558ffe84ddd1c9-mp3
// We don't need the first part, unless we're using the same function for files and images
const [_file, id, extension] = ref.split('-');
return `https://cdn.sanity.io/files/${PROJECT_ID}/${DATASET}/${id}.${extension}`
}
Querying the URL directly
However, if you can query for the file's document with GROQ that'd be easier:
*[(YOUR FILTER HERE)] {
file->{ url } // gets the URL from the referenced file
}
You can do the same with images, too.

Generating pdf in Angular 2

Me again with another Angular 2 question.
We are trying to generate a PDF file from a html source. I searched and searched trying to find an Angular 2 wrapper for the jsPdf or makePdf libraries, but I can't find any. Is there something I am missing? Is there a pure javascript way and is that good practice? Hope you guys can help.
Thanks in advance.
Francois
I was searching for the same thing, some weeks ago. I decided to do the generating on server-side (Node.js in my case). However you can do it on client-side, with jsPDF, like you mentioned.
Don't need a wrapper, just include the script and then access jsPDF through the window object. Wrapper will make it easier to test though.
I don't remember exactly but I thought it was something like this:
var doc = new window.jsPDF();
PDF is a complex file format, there may be some pdf parsers/generators built with js, but they will be limited & slow, your best bet is to do something server side.
HTML code:
<button type="button" (click)="downloadPdf()"
class="button">download</button>
Component.ts:
downloadPdf(){
this.authService.downloadPdf().subscribe(data => {
this.partnerDetails = data
} ); }
routes.js:
router.get('/downloadPdf',partnerCntrl.downloadPdf);
partnercntrl:
module.exports.downloadPdf = function (req, res) {
var fs = require('fs');
var pdf = require('html-pdf');
var html = fs.readFileSync('./test/businesscard.html', 'utf8');
var options = { format: 'Letter' };
pdf.create(html, options).toFile('./businesscard.pdf', function(err, res) {
if (err) return console.log(err);
console.log(res); // { filename: '/app/businesscard.pdf' }
});

writing content of local file to blob using javascript

I am trying to upload an excel file(named test1.xls) present in my computer in c drive at location->C:\test\test1.xls to google site(https://sites.google.com/xyz).To do so, I am using Google script editor and code shown below. The issue is that I am not able to pass the contents of file test1.txt at location C:\test\test1.txt instead of the text ("Here is some data")shown in code line shown below(var blob = Utilities.newBlob("Here is some data", "text/plain", "test1.xls");).Also what needs to be given instead of "text/plain" as it is excel file.Please let me know how to do that with code as I am new to google scripting/api coding,many thanks in advance.
CODE->
function doPost(e) {
var site = SitesApp.getSiteByUrl("https://sites.google.com/xyz"); Logger.log(site.getName());
var page = site.getChildren()[0];
// Create a new blob and attach it. Many useful functions also return
// blobs file uploads, URLFetch
var blob = Utilities.newBlob("Here is some data", "text/plain", "test1.xls");
try {
// Note that the filename must be unique or this call will fail
page.addHostedAttachment(blob);
}
catch(e){
Logger.log('Hosted attachment error msg:' +e.message);
}
}