简体   繁体   中英

Download file from servlet

In my servlet, I have a path where a file logs.txt exists like below,

String loc = "/u/xyz/workspace/FirstServlet/WebContent/WEB-INF/logs.txt";

and added the following line to my servlet and redirected response to jsp page,

String result = "<a href='"+loc+"' target='_blank'>Download result</a>";

Everything works fine but when I click the Download Result it returns a resource not found exception, I want to download logs.txt file to my client downloads folder.

What is my mistake?

Try this by passing path from servlet to Java script by using request.setAttribute(arg0, arg1)

<script type='text/javascript'> 
function saveTextAsFile()
{

   var textToWrite = "SOME TEXT YOU WANT TO WRITE"
   var textFileAsBlob = new Blob([textToWrite], {type:'.txt'});
   var fileNameToSaveAs = "my.txt";

  var downloadLink = document.createElement("a");
  downloadLink.download = fileNameToSaveAs;
   if (window.webkitURL != null)
   {
     downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
   }
   else
   {
     downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
     downloadLink.style.display = "none";
     document.body.appendChild(downloadLink);
  }

 }
</script>

Check this for downloading file from servlet

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM