使用原生servlet下载
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String path = request.getServletContext().getRealPath("/images");
String wj = "yy图标.jpg";
File file = new File(path, wj);
InputStream is=new FileInputStream(file);
OutputStream os = response.getOutputStream();
response.setHeader("content-disposition","attachment;filename=" +new String(wj.getBytes("utf-8"),"iso-8859-1"));
byte[] b = new byte[1024];
int len = is.read(b);
while(len!=-1){
os.write(b,0,len);
len = is.read(b);
}
os.close();
is.close();
}
使用SpringMVC下载
@RequestMapping("downFile")
public ResponseEntity<byte[]> export( String fileName) throws IOException {
String filePath = "E:/img/"+fileName;
HttpHeaders headers = new HttpHeaders();
File file = new File(filePath);
fileName = new String(fileName.getBytes("utf-8"),"iso-8859-1");
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", fileName);
ResponseEntity<byte[]> files = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
return files;
}
只用Struts2下载
public class DownFileAction {
private String fileName;
private InputStream inputStream;
public String down(){
inputStream = ServletActionContext.getServletContext().getResourceAsStream("/upload/"+fileName);
try {
fileName=new String(fileName.getBytes("UTF-8"),"ISO8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return "success";
}
}