How to force download file with Spring controller? - spring

i have a string controller to download a xml file but the download window is open everytime..
this is the code of my controller :
#RequestMapping(value = "/export", method = RequestMethod.POST)
#ResponseBody
public void export(HttpServletRequest request, HttpServletResponse response) throws JsonGenerationException,
JsonMappingException, IOException, DatatypeConfigurationException {
byte[] bytes = service.exportXML(getUsername());
String xmlFileName = "filename.xml";
response.setContentType("application/force-download");
response.setHeader("Content-Length", String.valueOf(bytes.length));
response.setHeader("Content-Disposition", "attachment; filename="+xmlFileName);
response.getOutputStream().write(bytes);
}
What i can do to browser never open download window and save the file immediately?

Its not possible from server side. Due to securtity reasons browser will not allow to auto download the files if specified in the browser itself.
For example, if you want to auto download and open a docx file type in your browser. Then check this link How can I open these .docx files from Chrome more quickly
Hope you will understand the limitation here.

Try adding this:
response.setHeader("Content-Transfer-Encoding", "binary");

Well i have earlier tried for txt files which opened directly. Nw they get saved instead of opening.

Related

Problems automatically converting to .txt when downloading xlsx files (excel files) within a Java (SpringBoot) server

When downloading a .xlsx file on a server, it automatically converts to .txt when asked for a save path.
You are currently working with SpringBoot, and if you click the download link through the tag in the view, click the .xlsx file.
The method of loading from the specified path.
The problem is that if you specify the href path for tag a as resource/static within the project, the .xlsx file will be downloaded without any problems.
However, if you route to a folder outside the project, the .xls file is downloaded normally, but. The xlsx file is automatically converted to .txt.
The path imported from the external folder is in the form of a request to the controller to return the actual file.
Below is the code that returns the file from the controller.
I'd like to ask those who know about this problem.
#GetMapping
public byte[] file(HttpServletRequest request) throws Exception {
FileInputStream in = new FileInputStream(new File().getPath() + "/filemanager/"
+ request.getRequestURI().split(request.getContextPath() + "/filemanager/")[1]);
byte[] image = IOUtils.toByteArray(in);
in close();
return image;
}

Download a csv file to a shared location, instead of locally, using Spring Boot API

I'm using Spring Boot to download a CSV file (using OpenCV) with a GetMapping request. There is a forced timeout setup on the application server and my request on large files will timeout; 504.
I want to try downloading the file to a shared location and see if that helps (if you have any other suggestions I'm open to new opionions).
my question is, how to hit the API and download the file to a shared location rather than downloading it locally.
here is the controller.
#GetMapping("/download")
public void download(HttpServletResponse r){
string fileName = "xyz.csv";
r.setContentType("text/csv");
r.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"");
CSVWriter csvWriter = new CSVWriter(r.getWriter());
downloadService.build(csvWriter); //returns csvWriter
}

How to download files properly using FileSystemResource in Spring?

I have this following code for downloading files :-
#Controller
public class FileController {
#RequestMapping(value = "/files/{file_name:.+}", method = RequestMethod.GET)
#ResponseBody
public FileSystemResource getFile(#PathVariable("file_name") String fileName) {
return new FileSystemResource("C:/Users/sourav/fileServer/"+fileName);
}
}
When I go to the link for the first time nothing is displayed .When I reload only a text file with name f.txt is downloaded instead of the pdf file. I want the pdf file to be displayed in the browser. How to solve this problem ?
I think you need to set the response headers. Otherwise there is no way for the browser to intuit the file format. Something like response.setContentType("application/pdf");.
your code is ok. I think if you try with pdf file it will work as you expected, it will be displayed in browser. I tested it and worked fine in Chrome and Firefox. May be your testing file is corrupted.
If you are using Spring Boot, you can add the MIME types of the files you want to download into spring.mvc.mediaTypes properties in the configuration file. For example:
spring.mvc.mediaTypes.yml=text/yaml
Source: https://github.com/spring-projects/spring-boot/issues/4220

MVC big file download

I am using ASP.net MVC 4.0. I want to download a file after clicking a download button/a link. The problem is that the file is big and I want to show a 'wait image' while downloading. How do i do it? I am getting the file as a stream? Should I use HTPResposneMessage with web-api or FileStreamResult with MVC? The issue is I want to be notified when the download finishes.
My file is being downloaded with a code as below:
public FileStreamResult Download(Guid id)
{
.......
return this.File(cab, "application/octet-stream", id + ".cab");
}
I want to show a spinner in javascript before beginning the download. My code is as follows:
self.IsDownloading(true);
var url = '/Download/' + id;
window.location = url;
self.IsDownloading(false);
But IsDownloading(false) is being executed before downloading the full file. How to make sure that it is done after the full file is downloaded?

Error in Dropbox file download using WebClient

I am working on downloading a text file hosted in dropbox. But i am getting a 400 Error code in the Completed function. I find the problem is with the dropbox hosted files only. I could download other sample text files hosted such as "http://wordpress.org/plugins/about/readme.txt".
Below is the code snippet i am using for downloading a text file from dropbox.
void downloadFile()
{
WebClient webClient = new WebClient();
NetworkCredential Credentials = new NetworkCredential(<username>, <password>, "<domain>);
webClient.Proxy = WebRequest.GetSystemWebProxy();
webClient.Proxy.Credentials = Credentials;
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
webClient.DownloadFileAsync(<downloadfileurl>, #"C:\test.txt");
}
private void Completed(object sender, AsyncCompletedEventArgs e)
{
if (e.Error == null)
{
MessageBox.Show("Successfully downloaded");
}
else
{
MessageBox.Show(e.Error.ToString());
}
}
The following is the error am getting :
System.Net.WebException: The remote server returned an error: (400) Bad Request.
at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.WebClient.GetWebResponse(WebRequest request, IAsyncResult result)
at System.Net.WebClient.DownloadBitsResponseCallback(IAsyncResult result)
Any support to tweak this problem will be highly appreciated.
Note : I have also tried using the WebRequest(POST), but same error there also.
Thanks in advance.
It looks like you're trying to use some sort of username/password authentication to download the file? Dropbox doesn't support any such thing.
You didn't share the URL you're trying to download. If it's a share link (a link created by a user who shared a file), it should just work with no authentication. If it's a file that hasn't been shared, you'll need to access it via the Dropbox API. See https://www.dropbox.com/developers to start learning about the Dropbox API.

Resources