public class FileUtils
{
private static final Logger log = LoggerFactory.getLogger(FileUtils.class);
public static String downloadFile(HttpServletRequest request, HttpServletResponse response, String filepath, boolean deleteOnExit) {
response.setCharacterEncoding(request.getCharacterEncoding());
response.setContentType("application/octet-stream");
File file = new File(filepath);
if(file.exists()) {
String name = getFileName(file.getName(), request);
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
response.setHeader("Content-Disposition", "attachment; filename=" + name);
IOUtils.copy(fis, response.getOutputStream());
response.flushBuffer();
return "success";
} catch (Exception e) {
log.error(e.getMessage(), e);
return "failure ";
} finally {
if (fis != null) {
try {
fis.close();
if (deleteOnExit) {
file.deleteOnExit();
}
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
}else {
return "file is not exists";
}
}
private static String getFileName(String fileName,HttpServletRequest request){
String userAgent = request.getHeader("user-agent").toLowerCase();
if (userAgent.contains("msie")) {
try {
fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("%20", "\\+").replaceAll("%28", "\\(")
.replaceAll("%29", "\\)").replaceAll("%3B", ";").replaceAll("%40", "@").replaceAll("%23", "\\#")
.replaceAll("%26", "\\&").replaceAll("%2C", "\\,").replaceAll("%24", "\\$")
.replaceAll("%25", "\\%").replaceAll("%5E", "\\^").replaceAll("%3D", "\\=")
.replaceAll("%2B", "\\+");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else if (userAgent.contains("like gecko")) {
try {
fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("%20", "\\+").replaceAll("%28", "\\(")
.replaceAll("%29", "\\)").replaceAll("%3B", ";").replaceAll("%40", "@").replaceAll("%23", "\\#")
.replaceAll("%26", "\\&").replaceAll("%2C", "\\,").replaceAll("%24", "\\$")
.replaceAll("%25", "\\%").replaceAll("%5E", "\\^").replaceAll("%3D", "\\=")
.replaceAll("%2B", "\\+").replaceAll("%5B", "\\[").replaceAll("%5D", "\\]")
.replaceAll("%7B", "\\{").replaceAll("%7D", "\\}");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else if (userAgent.contains("firefox")) {
try {
fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1").replaceAll("%20", "\\+")
.replaceAll("%28", "\\(").replaceAll("%29", "\\)").replaceAll("%3B", ";").replaceAll("%40", "@")
.replaceAll("%23", "\\#").replaceAll("%26", "\\&").replaceAll("%2C", "\\,")
.replaceAll("%24", "\\$");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return fileName;
}
}
public static void copy(InputStream inp, OutputStream out) throws IOException {
byte[] buff = new byte[4096];
int count;
while ((count = inp.read(buff)) != -1) {
if (count < -1) {
throw new RecordFormatException("Can't have read < -1 bytes");
}
if (count > 0) {
out.write(buff, 0, count);
}
}
}