Javaweb implementation File Download
Do not use <a> tags to download, this will open the file rather than download
For example:
<a href= "E:\MyDesktop\37fecd65330184de67d419a8d02e7081.jpg" > Download </a>
If I write this, the browser will open the picture directly, unless it is a file that cannot be opened by a browser
So we still need to use the Java itself to read and write files to download the file
<a href= "Downloadfile?filename=<s:property value= ' document_filename '/>" > Download </a>
Package com.cpsec.tang.chemical.action;
Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.FileNotFoundException;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import Java.text.SimpleDateFormat;
Import Java.util.Calendar;
Import java.util.List;
Import Java.util.Random;
Import Javax.annotation.Resource;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Import Org.apache.struts2.ServletActionContext;
Import Org.springframework.stereotype.Controller;
Import Com.cpsec.tang.chemical.biz.DocumentBiz;
Import com.cpsec.tang.chemical.entity.Document;
Import Com.cpsec.tang.chemical.util.Pager;
Import Com.opensymphony.xwork2.ActionSupport;
@Controller ("Documentaction") public class Documentaction extends actionsupport{private String filename;
Public String DownloadFile () {System.out.println (filename); try {httpservletresponse Response=servletactIoncontext.getresponse ();
Sets the file MIME type Response.setcontenttype (Servletactioncontext.getservletcontext (). GetMimeType (filename));
Set Content-disposition response.setheader ("Content-disposition", "attachment;filename=" +filename);
Gets the absolute path of the destination file String fullfilename = Servletactioncontext.getservletcontext (). Getrealpath ("/files/" + filename);
System.out.println (Fullfilename);
Read file InputStream in = new FileInputStream (fullfilename);
Read the target file and write the target file to the client outputstream out = Response.getoutputstream () by response;
Write file int b;
while ((B=in.read ())!=-1) {out.write (b);
} in.close ();
Out.close ();
catch (Exception e) {e.printstacktrace ();
return SUCCESS;
}
}
Thank you for reading, I hope to help you, thank you for your support for this site!