situation: clients has an existing windows app that uses csv files to transfer data back and forth and wants to persist in that manner.
challenge: After reading CSV data from server address process the data and generate a new CSV file and upload this to the 'backend'.
What I have tried: I have read just about every SO post on uploading files, but the problem is that if i just use the test data. Ie read the file, rename and save to backend it doesn't seem to work?
I use below code to get the blob for the file, this works fine and I can manipulate the data after retrieving it:
getCsvData3(url: string) {
let httpOptions: any = {
//observe: 'response',
headers: new HttpHeaders({ 'Content-Type': 'application/octet-stream' }),
params: new HttpParams(),
responseType: 'response'
}
return this.httpClient.get<string>(url, httpOptions);
}
Now I tried testing this by simply re-creating a File
object and attach it to the outgoing process. Using:
const type = { type: data.body.type };
const blob = new Blob([data.body], type);
const file = this.blobToFile(blob, 'test.csv')
Where blobToFile
looks like (I have tried several options to do this to no avail):
blobToFile(theBlob: Blob, fileName: string): File {
var b: any = theBlob;
//A Blob() is almost a File() - it's just missing the two properties below which we will add
b.lastModifiedDate = new Date();
b.name = fileName;
//Cast to a File() type
return <File>theBlob;
}
Subsequently I attach the file to the httpClient.Post()
call:
uploadFile(file: File, fileNum: number) {
const formData = new FormData();
formData.append("the_file", file, file.name);
this.dataService.uploadWithProgress(formData)
.subscribe(event => {
if (event.type === HttpEventType.UploadProgress) {
console.log(Math.round(100 * event.loaded / event.total));
//let percentUploaded = Math.round(100 * event.loaded / event.total);
} else if (event instanceof HttpResponse) {
console.log(file.name + ', Size: ' + file.size + ', Uploaded URL: ' + event.body.link);
//this.fileUploadSuccess();
}
},
err => console.log(err)
);
}
But no matter what I try, I do not get this to work?
I have also tried to use the MediaFilePicker of NativeScript but that too gives all sorts of nightmares? See this question.
I have a NativeScript core app that uploads a JSON file and is received/processed by a small PHP file on the host. You can ignore the authentication code, and you'll have to convert to Angular, but this should at least serve as a working example:
/**
* Post app's eventData object to the web, so that it may live-update apps in the field.
* Uses basic authentication; requires .htaccess and .htpasswd files in host directory
* @param {object} eventData - app's event-specific data object, from event-data.js
* @return void
*/
exports.postEventData = function (eventData) {
dialogs.confirm({
title: "myutils.postEventData",
message: "Post app's eventData object to web?",
okButtonText: "Yes",
cancelButtonText: "No"
}).then((result) => {
if (result) { // if Yes selected
let content = JSON.stringify(eventData);
http.request({
url: eventData.subdomain + eventData.postPath, // path to receive.php
method: "POST",
headers: {
"Content-Type": "application/octet-stream",
"Authorization": "Basic " + credentials,
},
content: content
}).then((response) => {
console.log(response.content.toString());
dialogs.alert({
title: "myutils.postEventData",
message: "EventData posted successfully.",
okButtonText: "OK"
}).then(() => { return; });
}, (err) => {
console.log(err);
dialogs.alert({
title: "myutils.postEventData",
message: "EventData post failed. \n\n " + err,
okButtonText: "OK"
}).then(() => { return; });
}); // end http.request
} // end Yes selected
}); // end confirm.then
} // end postEventData
And here's the PHP file:
<?php
/**
* Receive json file via http POST request and save contents to current directory.
* @author David Cole <dlcole33@gmail.com>
*/
if (empty($_POST) && empty($_GET)) { // Both POST and GET arrays should be empty
$outputFilename = "eventData.json";
$outputFile = getcwd() . "/" . $outputFilename;
$fileData = file_get_contents('php://input');
$fp = fopen($outputFile, "w");
fwrite($fp, $fileData);
fclose($fp);
if (file_exists ( $outputFile )) {
echo "File " . $outputFile . " created on host.\n";
} else {
echo "File " . $outputFile . " creation failed.\n";
}
// echo $fileData;
} else {
echo '$_POST / $_GET check failed.\n';
}
exit();
?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.