index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件下载</title>
</head>
<body>
<div class="down">
<h1><a href="/testDownload">前往下载</a><br/></h1>
</div>
</body>
</html>
DownController.java
package com.bskj.lg.controller;
import com.bskj.lg.tools.DateU;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
@Controller
public class DownController {
@RequestMapping(value="/testDownload", produces="application/vnd.android.package-archive")
public ResponseEntity<byte[]> testDownload(HttpServletRequest request, HttpServletResponse resp) throws IOException{
String filename="/lgsys.apk";
String lj = ClassUtils.getDefaultClassLoader().getResource("static/update").getPath();
String path=lj+filename;
System.out.println(path);
File f=new File(path);
InputStream in = new FileInputStream(f);
ResponseEntity<byte[]> response=null ;
try {
byte[] b=new byte[in.available()];
HttpHeaders headers = new HttpHeaders();
filename = new String(filename.getBytes(),"utf-8");
//以下的类型必须要设置,要不不能在android机上正常下载的
String fname = "lgsys"+ DateU.getCurrentDate()+".apk";
headers.add("Content-Disposition", "attachment;filename="+fname);
HttpStatus statusCode= HttpStatus.OK;
while(in.read(b) != -1){
response = new ResponseEntity<byte[]>(b, headers, statusCode);
}
resp.reset();
return response;
} catch (Exception e) {
e.printStackTrace();
throw new IOException("文件下载失败");
}
}
}
DateU.java
package com.bskj.lg.tools;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateU {
private static SimpleDateFormat sf=null;
/*
* 获取系统时间
* */
public static String getCurrentDate(){
Date d=new Date();
sf=new SimpleDateFormat("yyyyMMdd-HH:mm");
return sf.format(d);
}
/**
* 时间戳转换成时间字符串
*/
public static String getDateToString(long time){
Date d=new Date(time);
sf=new SimpleDateFormat("yyyyMMdd-HH:mm");
return sf.format(d);
}
/**
* 时间字符串转换成时间戳
*/
public static long getStringToDate(String time){
sf=new SimpleDateFormat("yyyyMMdd-HH:mm");
Date date=new Date();
try {
date=sf.parse(time);
}
catch (Exception e){
}
return date.getTime();
}
}