I am trying to download some blob by creating a link in clicking it at runtime.
This works fine in chrome and FF but nothing downloads in IE11.
var blob = new Blob([], { type: 'text/csv' });
var link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = 'Test.csv';
document.body.appendChild(link);
link.click();
Try open http://jsfiddle.net/rq8460cL/3/ in chrome/FF and it will download file but IE nothing happens.
Any Help please???
Related
My model is held in a JavaScript object on the client side, where the user can edit its properties via the UI controls. I want to offer the user an option to download a JSON file representing the model they're editing. I'm using MVC core with .net 6.
What I've tried
Action method (using Newtonsoft.Json to serialize the model to JSON):
public IActionResult Download([FromForm]SomeModel someModel)
{
var json = JsonConvert.SerializeObject(someModel);
var characters = json.ToCharArray();
var bytes = new byte[characters.Length];
for (var i = 0; i < characters.Length; i++)
{
bytes[i] = (byte)characters[i];
}
var stream = new MemoryStream();
stream.Write(bytes);
stream.Position = 0;
return this.File(stream, "APPLICATION/octet-stream", "someFile.json");
}
Code in the view to call this method:
<button class="btn btn-primary" onclick="download()">Download</button>
And the event handler for this button (using jQuery's ajax magic):
function download() {
$.ajax({
url: 'https://hostname/ControllerName/Download',
method: 'POST',
data: { someModel: someModel },
success: function (data) {
console.log('downloading', data);
},
});
}
What happened
The browser console shows that my model has been posted to the server, serialized to JSON and the JSON has been returned to the browser. However no file is downloaded.
Something else I tried
I also tried a link like this to call the action method:
#Html.ActionLink("Download", "Download", "ControllerName")
What happened
This time a file was downloaded, however, because ActionLink can only make GET requests, which have no request body, the user's model isn't passed to the server and instead the file which is downloaded represents a default instance of SomeModel.
The ask
So I know I can post my model to the server, serialize it to JSON and return that JSON to the client, and I know I can get the browser to download a JSON-serialized version of a model, but how can I do both in the same request?
Edit: What I've done with the answer
I've accepted Xinran Shen's answer, because it works as-is, but because I believe that just copying code from Stack Overflow without understanding what it does or why isn't good practice, I did a bit of digging and my version of the saveData function now looks like this:
function saveData(data, fileName) {
// Convert the data to a JSON string and store it in a blob, a file-like
// object which can be downloaded without it existing on the server.
// See https://developer.mozilla.org/en-US/docs/Web/API/Blob
var json = JSON.stringify(data);
var blob = new Blob([json], { type: "octet/stream" });
// Create a URL from which the blob can be downloaded - see
// https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL
var url = window.URL.createObjectURL(blob);
// Add a hidden hyperlink to the page, which will download the file when clicked
var a = document.createElement("a");
a.style = "display: none";
a.href = url;
a.download = fileName;
document.body.appendChild(a);
// Trigger the click event on the hyperlink to download the file
a.click();
// Release the blob's URL.
// Browsers do this when the page is unloaded, but it's good practice to
// do so as soon as it's no longer needed.
window.URL.revokeObjectURL(url);
// Remove the hidden hyperlink from the page
a.remove();
}
Hope someone finds this useful
First, Your code is right, You can try to access this method without ajax, You will find it can download file successfully,But You can't use ajax to achieve this, because JavaScript cannot interact with disk, you need to use Blob to save the file. change your javascript like this:
function download() {
$.ajax({
url: 'https://hostname/ControllerName/Download',
method: 'Post',
data: { someModel: someModel },,
success: function (data) {
fileName = "my-download.json";
saveData(data,fileName)
},
});
}
var saveData = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, fileName) {
var json = JSON.stringify(data),
blob = new Blob([json], {type: "octet/stream"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
};
}());
I think you may need FileStreamResult, also you need to set the MIME type to text file or json file.
// instead of this
return this.File(stream, "APPLICATION/octet-stream", "someFile.json");
// try this
return new FileStreamResult(stream, new MediaTypeHeaderValue("text/plain"))
{
FileDownloadName = "someFile.txt"
};
// or
return new FileStreamResult(stream, new MediaTypeHeaderValue("application/json"))
{
FileDownloadName = "someFile.json"
};
Reference: https://www.c-sharpcorner.com/article/fileresult-in-asp-net-core-mvc2/
I am trying to download pdf file from Laravel api with vue front end. Here is my vue code
methods: {
downloadAttachment(file) {
axios({
url: 'http://localhost:8000/storage/app/public/files/owwhz8JkFjyTuE4SNMytTKjXbVWLLIkaPnaSUF9b.pdf',
method: 'GET',
responseType: 'blob', // important
}).then((response) => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'file.pdf');
document.body.appendChild(link);
link.click();
});
}
}
Now when i execute the method, it downloads a pdf file but says "Failed to load pdf document"
what's the error here ? Do I need to change anything in Laravel Api ?
Assuming you already created the symlink in Laravel, I think you are missing the type when creating your Blob instance.
So change your code from
const url = window.URL.createObjectURL(new Blob([response.data]));
to
const url = window.URL.createObjectURL(new Blob([response.data], { type: 'application/pdf' }));
Also check your URL. If it's a public file, strip off the /app/public/ part, so that your URL becomes http://localhost:8000/storage/files/...
When trying to download a large file in IE11, I am getting the error
Not enough storage is available to complete this operation
This works as expected in Google Chrome.
I have the following code in JS
var byteStr = event.target.response;
var byteArray = byteStr.replace('[', '').replace(']', '').split(','); //error occurs at this line
var fileName = event.target.getResponseHeader('filename');
var uint8_array = new Uint8Array(byteArray);
var bb = new Blob([uint8_array], {
type: 'application/octet-stream'
});
if (window.navigator['msSaveBlob']) {
window.navigator['msSaveBlob'](bb, fileName);
} else {
this.download(window.URL.createObjectURL(bb), fileName);
}
Is there a way I can modify my code to be able to download large files (file content inside the response) without having to change any of the IE settings manually?
i have this code for convert website to exe file using electon js but i have problem
inside the website there are .swf files and i search alot about how i can run .swf files but it's not work
i was traing by plugin it's name "Pepper Flash Plugin"
this is the url for this plugin
https://electron.atom.io/docs/tutorial/using-pepper-flash-plugin/
and i was searsh about "pepflashplayer.dll"
and put it on the root on prject directory and also not work
any help please
file:main.js
'use strict';
const electron = require('electron');
const path = require('path');
const app = electron.app; // Module to control application life.
const BrowserWindow = electron.BrowserWindow; // Module to create native browser window.
// Specify flash path, supposing it is placed in the same directory with main.js.
let pluginName
switch (process.platform) {
case 'win32':
pluginName = 'pepflashplayer.dll'
break
case 'darwin':
pluginName = 'PepperFlashPlayer.plugin'
break
case 'linux':
pluginName = 'libpepflashplayer.so'
break
}
app.commandLine.appendSwitch('ppapi-flash-path', path.join(__dirname, pluginName))
var mainWindow = null;
app.on('ready', function() {
mainWindow = new BrowserWindow({width: 1100, height: 900, webPreferences: {
plugins: true
}});
// and load the index.html of the app.
mainWindow.loadURL('file://' + __dirname + '/cd/cd/START.html');
});
case 'win32':
pluginName = 'pepflashplayer.dll'
You simply need to put in the directory to where your dll file is located
Currently (June 2017) it is stored at:
C:\Users\USER\AppData\Local\Google\Chrome\User Data\PepperFlash\26.0.0.126
case 'win32':
pluginName = 'C:\Users\USER\AppData\Local\Google\Chrome\User Data\PepperFlash\26.0.0.126\pepflashplayer.dll'
OR
copy the dll to your app's directory and point it to there
case 'win32':
pluginName = './pepflashplayer.dll'
I'am trying to run a web server and open an HTML file via gulp-connect and gulp-open.
The server is running, the html is opened correctly but not through the server but as a file from the HDD.
On the URL address bar I can see: "file:///Users/...." instead of "http://localhost:9000/"
Does anyone know what could be the issue ?
Thanks for your help
"use strict";
var gulp = require('gulp');
var gulpConnect = require('gulp-connect'); // run a local dev server
var gulpOpen = require('gulp-open'); // open a URL in the browser
var config ={
port:'9000',
baseDevUrl:'http://localhost',
paths: {
html: './src/*.html',
dist:'./dist'
}
};
// start a local development server
gulp.task('connect',function(){
gulpConnect.server({
root:['dist'],
port: config.port,
base: config.baseDevUrl,
livereload:true
});
});
gulp.task('open',['connect'],function(){
gulp.src('dist/index.html')
.pipe(gulpOpen('',{ url: config.baseDevUrl +':'+ config.port +'/', app:'google chrome'}));
});
gulp.task('html',function(){
gulp.src(config.paths.html)
.pipe(gulp.dest(config.paths.dist))
.pipe(gulpConnect.reload());
});
gulp.task('watch',function(){
gulp.watch(config.paths.html,['html']);
});
gulp.task('default',['html','open','watch']);
OK here is how you open things:
gulp.src('./index.html').pipe(gulpOpen({uri: 'http://localhost:8888', app: 'Google Chrome'}));
You've got an extra first parameter in gulpOpen and url should be uri
Good luck!