Recently made a website, about the retrieval of a system, which involves the file download and view (PDF file), encountered some problems, and now share with you my solution:
File download In general there are two ways (I think Ah, don't take it seriously),
One way is through hyperlinks: <a href= "<%=basepath%>/download/file name" > download </a> this way you can download the file under the root path under Download,
However, this download can only download. rar files, when downloading PDFs or images, he does not open that file, so this way is generally used to see the full text or preview the full text of the function.
The second way is to use the background code, this way first to request to the background, I will take the SSH framework as an example, to demonstrate:
First, the Code on the page, I used a hyperlink.
<a href= "download!downloadfile.action?filename= file name to download" > Downloads </a>
After that is the background code
public string DownloadFile () {
string filename = Servletactioncontext.getrequest (). GetParameter ("filename" ); //get the file name passed by the foreground
HttpServletRequest request = Servletactioncontext.getrequest ();//Get Request Object
HttpServletResponse Response=servletactioncontext.getresponse (); Gets the Response object
Response.setheader ("Content-disposition", "attachment;filename=" +filename); //
String Fullfilename=request.getsession (). Getservletcontext (). Getrealpath ("") + "\\download\\" +filename;
try{
InputStream in = new FileInputStream (fullfilename);
OutputStream out = Response.getoutputstream ();
//write file
int b;
while ((B=in.read ())! =-1)
{
Out.write (b);
}
In.close ();
Out.close ();
}
catch (Exception e) {
}
Return "rdate"; //
}
This will enable the download of the file (you can download the file under the root path under Download), in Windows completely no problem (I personally tried)
--------------------------------------------------------------------------------------------------------------- ---------------------------------
After I have been happy to deploy this project to the server to test the (Linux system), then the problem came, the project on the server can not download, depressed, and then began to find a solution,
Finally found the problem, the original Linux system directory is the XXX/XXX/XXX format and Windows is the XXX\XXX\XXX format, so to deploy to the Linux system under the program has to be modified, the
String fullfilename=request.getsession (). Getservletcontext (). Getrealpath ("") + "\\download\\" +filename; this sentence \ \ You can do it.
String fullfilename=request.getsession (). Getservletcontext (). Getrealpath ("") + "/download/" +filename;
Well, done, what's wrong with the place welcome everyone to point out that everyone together to learn
Also can add oneself qq:212966054
Javaweb file download deployment to server file download problem