Javaweb file download
Don't say downloading with the <a> tag, this will open the file instead of downloading
For example:
<a href="E:/MyDesktop/37fecd65330184de67d419a8d02e7081.jpg">Download</a>
If I write this way, the browser will open the image directly unless it is a file that cannot be opened by a browser
So we still need to use Java itself to read and write files to download files
<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.steretype.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(); //Set the file MIME type response.setContentType(ServletActionContext.getServletContext().getMimeType(filename)); //Set Content-Disposition response.setHeader("Content-Disposition", "attachment;filename="+filename); //Get the absolute path of the target file String fullFileName = ServletActionContext.getServletContext().getRealPath("/files/" + filename); //System.out.println(fullFileName); //Read the file InputStream in = new FileInputStream(fullFileName); //Read the target file and write the target file to the client through response OutputStream out = response.getOutputStream(); //Write the 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 it can help you. Thank you for your support for this site!