在下面的代码中,如果我将文件输出格式更改为output.csv,文件将自动下载,但如果我将格式更改为output.txt,文件将显示在浏览器上。如何自动下载输出。 txt文件
由于 csv 文件正在下载,相同代码的 txt 文件有什么问题
def downloadcsv(request):
try:
response = {}
output = fq_name+"/"+ "output.txt"
os.system(cmd)
logger.debug(file_name)
response.update({'status':0,'message': 'Success','file_name' : output})
except Exception as e:
response['message'] = "Exception while processing request"
response['status'] = 2
logger.exception(e)
return HttpResponse(JsonResponse(response), content_type="application/json")
$.post("/reports/downloadcsv/", snddata,
function callbackHandler(data, textstatus)
{
if (data.status == 0)
{
document.location.href = data.file_name;
//document.getElementById('my_iframe').src = data.file_name;
}
else if (data.status == 1 || data.status == 2)
{
$('#loading').hide();
alert('Error while processing data');
}
$('#loading').hide();
},
"json"
);
最佳答案
顺便说一句,为什么对 .txt 文件使用“application/json”而不是 .json?
很难可靠地控制不同浏览器对服务器端的特定文件或内容类型执行的操作,因为浏览器根据用户的偏好进行操作:在浏览器中打开、打开另存为对话框、在第 3 方程序中打开,使用插件等处理
您可以尝试HTML5下载属性:http://www.w3schools.com/TAgs/att_a_download.asp
此处提出的其他解决方案:Force to open "Save As..." popup open at text link click for pdf in HTML
关于django - 从django自动下载txt文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39346705/