csvファイルの文字列をダウンロードさせるために、以下のコードを用意しました。
exportData = 'data:text/csv;charset=utf-8,';
exportData += 'some csv strings';
encodedUri = encodeURI(exportData);
newWindow = window.open(encodedUri);
クライアントがこのコードを実行すると、空白のページが生成され、csvファイルのデータのダウンロードが開始されるのは問題ありません。
そこで、次のようなJSONオブジェクトを使用してこれを実行しようとしました。
exportData = 'data:text/json;charset=utf-8,';
exportData += escape(JSON.stringify(jsonObject));
encodedUri = encodeURI(exportData);
newWindow = window.open(encodedUri);
しかし、JSONデータが表示されたページが表示されるだけで、ダウンロードはされません。
いくつか調べてみたところ、こちらが動作すると主張していますが、私のコードに違いは見当たりません。
私のコードに何か欠けているのでしょうか?
私の質問を読んでくれてありがとうございます:)
これが私のアプリケーションのためにそれを解決した方法です:
HTML:
< a id = "downloadAnchorElem" style = "display:none">< / a>
。
JS(ここではjQueryではなく、純粋なJS):
var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(storageObj));
var dlAnchorElem = document.getElementById('downloadAnchorElem');
dlAnchorElem.setAttribute("href", dataStr );
dlAnchorElem.setAttribute("download", "scene.json");
dlAnchorElem.click();
この場合、「storageObj」は保存するjsオブジェクトであり、「scene.json」は結果のファイルの単なる例名です。
このアプローチには、他の提案されたアプローチよりも次の利点があります。
jsからある時点で自動的にダウンロードをトリガーしたいので、明示的にクリックせずにこの動作が必要でした。
JSソリューション(HTMLは不要):
function downloadObjectAsJson(exportObj, exportName){
var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(exportObj));
var downloadAnchorNode = document.createElement('a');
downloadAnchorNode.setAttribute("href", dataStr);
downloadAnchorNode.setAttribute("download", exportName + ".json");
document.body.appendChild(downloadAnchorNode); // required for firefox
downloadAnchorNode.click();
downloadAnchorNode.remove();
}
答えが見つかりました。
var obj = {a: 123, b: "4 5 6"};
var data = "text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(obj));
$('<a href="data:' + data + '" download="data.json">download JSON</a>').appendTo('#container');
は、私の場合、問題なく動作するようです。
All credit goes to @cowboy-ben-alman, who is the author of the code above .
これは純粋なJSバージョン(カウボーイから改作)になります。
var obj = {a: 23, b: "4 5 6"};
var data = "text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(obj));
var a = document.createElement('a');
a.href = 'data:' + data;
a.download = 'data.json';
a.innerHTML = 'download JSON';
var container = document.getElementById('container');
container.appendChild(a);
[
/embedded/result,js,html,css/">あなたは使ってみることができます:
-ネイティブJavaScript APIのBlobコンストラクターと。
-FileSaver.js saveAs()
メソッド。
HTML要素をまったく処理する必要はありません。
var data = {
key: 'value'
};
var fileName = 'myData.json';
// Create a blob of the data
var fileToSave = new Blob([JSON.stringify(data)], {
type: 'application/json',
name: fileName
});
// Save the file
saveAs(fileToSave, fileName);
JSONをきれいに印刷したい場合は、この回答に従って、次のコマンドを使用できます。
JSON.stringify(data,undefined,2)
以下は私にとってはうまくいきました。
/* function to save JSON to file from browser
* adapted from http://bgrins.github.io/devtools-snippets/#console-save
* @param {Object} data -- json object to save
* @param {String} file -- file name to save to
*/
function saveJSON(data, filename){
if(!data) {
console.error('No data')
return;
}
if(!filename) filename = 'console.json'
if(typeof data === "object"){
data = JSON.stringify(data, undefined, 4)
}
var blob = new Blob([data], {type: 'text/json'}),
e = document.createEvent('MouseEvents'),
a = document.createElement('a')
a.download = filename
a.href = window.URL.createObjectURL(blob)
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':')
e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
a.dispatchEvent(e)
}
そして、そのように呼び出します。
saveJSON(myJsonObject, "saved_data.json");
最近、大きなフォームのすべての値のjsonファイルをダウンロードするボタンを作成する必要がありました。 IE / Edge / Chromeで作業するには、これが必要でした。 これは私がやったことです。
function download(text, name, type)
{
var file = new Blob([text], {type: type});
var isIE = /*@cc_on!@*/false || !!document.documentMode;
if (isIE)
{
window.navigator.msSaveOrOpenBlob(file, name);
}
else
{
var a = document.createElement('a');
a.href = URL.createObjectURL(file);
a.download = name;
a.click();
}
}
download(jsonData, 'Form_Data_.json','application/json');
ファイル名とエッジの拡張子に1つの問題がありましたが、執筆時点では、これは修正される予定のEdgeのバグであるように思われました。
これが誰かを助けることを願っています。
最新のブラウザーのみを対象とする人のためのシンプルでクリーンなソリューション:
function downloadTextFile(text, name) {
const a = document.createElement('a');
const type = name.split(".").pop();
a.href = URL.createObjectURL( new Blob([text], { type:`text/${type === "txt" ? "plain" : type}` }) );
a.download = name;
a.click();
}
downloadTextFile(JSON.stringify(myObj), 'myObj.json');
反応:レンダリングメソッドで必要な場所にこれを追加します。
•オブジェクト状態:
<a
className="pull-right btn btn-primary"
style={{ margin: 10 }}
href={`data:text/json;charset=utf-8,${encodeURIComponent(
JSON.stringify(this.state.objectToDownload)
)}`}
download="data.json"
>
DOWNLOAD DATA AS JSON
</a>
•オブジェクト小道具:
<a
className="pull-right btn btn-primary"
style={{ margin: 10 }}
href={`data:text/json;charset=utf-8,${encodeURIComponent(
JSON.stringify(this.props.objectToDownload)
)}`}
download="data.json"
>
DOWNLOAD DATA AS JSON
</a>
classNameとstyleはオプションで、必要に応じてスタイルを変更します。