下载文件
一、字节数组byte[]下载
1. 数据库读取到字节数组byte[]
2. 设置response的返回头
response.setContentType(contentType + "; charset=application/octet-stream");
fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), "ISO8859-1");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
response.setHeader("Access-Control-Expose-Headers", "filename");
response.setHeader("filename", fileName);
3. 将字节数据设置到response中即可
OutputStream outputStream = response.getOutputStream();
outputStream.write(bytes);
outputStream.flush();
二、流inputstream下载
1. 拿到的inputstream流
2. 设置reponse的返回头(同上)
3. 将inputstream设置到response中
OutputStream outputStream = response.getOutputStream();
IOUtils.copy(inputStream, outputStream);
outputStream.flush();
三、文件下载
1. 拿到的file文件
2. 将file文件转换为流
FileInputStream fileInputStream = new FileInputStream(file);
3. 设置reponse的返回头(同上)
4. 将inputstream设置到response中(同上)
5. 关闭文件流
fileInputStream.close();
相关技能:
下载文件获取真实文件名
public String getFileName(String urlStr){
String fileName = null;
try {
URL url = new URL(urlStr);
URLConnection uc = url.openConnection();
fileName = uc.getHeaderField("Content-Disposition");
fileName = new String(fileName.getBytes("ISO-8859-1"), "GBK");
fileName = URLDecoder.decode(fileName.substring(fileName.indexOf("filename=")+9),"UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
return fileName;
}
获取文件大小:
conn.getContentLength();
上传文件