Download .msg files in client side Reactjs - javascript

I have a server containing multiple .msg files
I want to enable the user to download them in the client side using the following code:
const download = (fileName) => {
var FileSaver = require('file-saver');
FileSaver.saveAs(constants.filesUploadUrl + fileName, fileName);
}
The download is working fine with all data types except .msg files
It gives me "Failed - No file"
Is there a way to enable downloading .msg files in client side?

It turned out that I needed to convert the content type into "application/vnd.ms-outlook"
As it wasn't recognized via Google chrome as .msg
My backend ASP.Net Core
Code for mapping MIME Type:
}
var provider = new FileExtensionContentTypeProvider();
provider.Mappings[".msg"] = "application/vnd.ms-outlook";
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
ContentTypeProvider = provider
});

Related

File not opening after download: ReactJs + Spring Boot

I am developing a web application and one of my use cases is for users to have the ability to upload and download files from the server. I'm using ReactJs and Spring Boot.
Front-End code:
downloadFileClicked(id, fileName, fileType){
TestDataService.downloadFile(id)
.then(response=>{
console.log(response)
const file = new Blob(
[response.data],
{type: fileType}
)
let url = window.URL.createObjectURL(file)
let a = document.createElement('a')
a.href=url
a.download= fileName
a.click()
})
}
Back-End code:
#GetMapping("/downloadFile/{fileId:.+}")
public ResponseEntity<Resource> downloadFile(#PathVariable Long fileId, HttpServletRequest request ){
//Load file as a resource
DatabaseFile databaseFile = fileStorageService.getFile(fileId);
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(databaseFile.getFileType()))
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\""+databaseFile.getFileName()+"\"")
.body(new ByteArrayResource(databaseFile.getData()));
}
When the user clicks download - the file does indeed download and seemingly in the correct format but when each application tries to open the file I am faced with such errors as the file format is not supported or the file is corrupt.
The file data is being stored as a byte array in a MySQL database. I have tried a number of different methods to download the file but I have encountered the same error each time. Any help would be greatly appreciated!

How to load local data into js file variable?

I am doing an IoT device simulator and I have a dataset of readings that I want to send to the IoT hub. The file I am working on is here. I change it to
var data = ???;
data.forEach(function(e){
state.pressure = e;
updateState(state);
log("Pressure increased to " + state.pressure);
sleep(1000);
})
I have a file with all the data I need. Is there any way I can load the data into the file as a variable (var data) of the current js file.
function getData() {
var data =
{
"example": [999,999]
};
return data.example;
}
export function getEventData() {
getData();
}
It give me an error : JS function failure, {"Message":"Line 14: Unexpected reserved word","FullName":"Jint.Parser.ParserException"}
and the 14 line : import { getEventData } from "./HavenEventData"
There are three different supported languages to upload data into IOT hub, this would also work for the simulation scenario, the current documentation shows .NET, JAVA, Node.js.
Once you associate an Azure storage account to the IoT Hub, IoT hub generates a SAS URI. A device can use this SAS URI to securely upload a file to a blob container. The IoT Hub service and the device SDKs coordinate the process that generates the SAS URI and makes it available to a device to use to upload a file.
Source is here, I'd recommend to check it out since it has examples.
an example of a Method using C# is as follow:
private static async void SendToBlobAsync()
{
string fileName = "image.jpg";
Console.WriteLine("Uploading file: {0}", fileName);
var watch = System.Diagnostics.Stopwatch.StartNew();
using (var sourceData = new FileStream(#"image.jpg", FileMode.Open))
{
await deviceClient.UploadToBlobAsync(fileName, sourceData);
}
watch.Stop();
Console.WriteLine("Time to upload file: {0}ms\n", watch.ElapsedMilliseconds);
}
Let me know if this helps.
you need to do var data = require('path_to_you_file') (but i am assuming its a json file) is it ?

Open an .ics file via JavaScript / Typescript

I have a downloaded ICS file via Angular2 on a desktop machine. I am trying to automatically open this file, at the moment the behavior i am seeing is that the file just downloads - it can be then opened. However, I would like to automatically invoke the default Mail client.
Code:
openICS(data: Response) {
let payload = data.text();
let blob = new Blob([payload], { type: 'text/calendar' });
let url = window.URL.createObjectURL(blob);
window.open(url, '_blank');
}
Can anyone help?
Cheers
KH

pdftron webviewer - how to save the whole edited pdf to server with php

I am currently a developing an application that is using a PDFTron webviewer. Is there anyway to save the edited pdf edited with pdftron webviewer to the server?
There is a feature of pdftron that saves annotations to the server, but I need to save the whole pdf with the edits to the server.
You could call the following function from a WebViewer config file to get the PDF data as a blob. Once you have the blob you can refer to one of the many examples online of how to upload a blob to a server.
function uploadPDF() {
var docViewer = readerControl.docViewer;
var options = {
xfdfString: docViewer.getAnnotationManager().exportAnnotations()
};
var doc = docViewer.getDocument();
doc.getFileData(options).then(function(data) {
var arr = new Uint8Array(data);
var blob = new Blob([arr], {
type: 'application/pdf'
});
// upload blob here
});
}

Download PDF file in HTML5/Javascript MOBILE application

I need to create functionality which allows a user to download a PDF file from my HTML5/JavaScript-based mobile application. I will be getting the PDF file as a Base 64 encoded byte stream. How can I allow the user to download the PDF to their device upon clicking a button in the page?
For IOS:
You can download a pdf on iPhone apps and show it in a WebView.
Some ways are listed at this (linked) question. You can also find there how to put the pdf in a folder of the device/iPhone running the app: How to download PDF and store it locally on iPhone?
let request = URLRequest(url: URL(string: "http://www.msy.com.au/Parts/PARTS.pdf")!)
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let task = session.dataTask(with: request, completionHandler: {(data, response, error) in
if error == nil{
if let pdfData = data {
let pathURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("\(filename).pdf")
do {
try pdfData.write(to: pathURL, options: .atomic)
}catch{
print("Error while writting")
}
DispatchQueue.main.async {
self.webView.delegate = self
self.webView.scalesPageToFit = true
self.webView.loadRequest(URLRequest(url: pathURL))
}
}
}else{
print(error?.localizedDescription ?? "")
}
}); task.resume()
For Android:
There are many ways to do it for Android. This one should work in most cases without any issue:
URL u = new URL("http://www.path.to/a.pdf");
//open a connection
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
FileOutputStream f = new FileOutputStream(new File(root,"file.pdf"));
//read the file
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ( (len1 = in.read(buffer)) > 0 ) {
f.write(buffer,0, len1);
}
f.close();
This other one-line option works to download a pdf in android, but seems to have different behavior depending on the device and other installed apps (pdf reader):
`startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("path/filename.pdf")));`
I used this question and it's reply to get a working code example. You can find a long answer at the bottom of the post with many different use-cases and their solutions explained at the same post.: How to download a pdf file in Android?

Categories