Java Web应用对于文件一般有专门的文件服务器。在下载的时候下载静态文件直接打开文件服务器给的链接就好,对与动态文件设置http协议头直接写文件就好。
动态文件下载关键代码:
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;fileName=" + downloadFileName);
try {
InputStream inputStream = new FileInputStream(file);
OutputStream os = response.getOutputStream();
byte[] b = new byte[4096];
int length;
while ((length = inputStream.read(b)) > 0) {
os.write(b, 0, length);
}
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}finally
{
if(os!=null) {
try {
os.close();
}
catch(IOException e){
e.printStackTrace();
}
}
}
静态文件下载示例:
对于静态文件可以直接打开链接文件或者转为各种下载工具的下载链接,以下是各种常用工具下载链接转换代码:
public static String getThunderUrl(String sourceUrl)
{
if (sourceUrl==null || sourceUrl.equals(""))
{
return null;
}
String sourceUrlEncoder = Base64Helper.getBase64Str("AA"+sourceUrl+"ZZ");
return "thunder://"+sourceUrlEncoder;
}
public static String getFlashGetUrl(String sourceUrl)
{
if (sourceUrl==null || sourceUrl.equals(""))
{
return null;
}
String sourceUrlEncoder = Base64Helper.getBase64Str("[FlashGet]"+sourceUrl+"[FlashGet]");
return"flashget://"+sourceUrlEncoder;
}
public static String getQqdlUrl(String sourceUrl){
if (sourceUrl==null || sourceUrl.equals(""))
{
return null;
}
String sourceUrlEncoder = Base64Helper.getBase64Str(sourceUrl);
return"qqdl://"+sourceUrlEncoder;
}
Base64Helper代码:
public class Base64Helper {
public static String getBase64Str(String source)
{
if (source == null || source.equals("")){
return null;
}
else
{
return (new BASE64Encoder()).encode(source.getBytes());
}
}
public static String getStrFromBase64(String base64Str)
{
if (base64Str == null || base64Str.equals(""))
return null;
BASE64Decoder decoder = new BASE64Decoder();
try {
byte[] b = decoder.decodeBuffer(base64Str);
return new String(b);
} catch (Exception e) {
e.printStackTrace();
} return null;
}
}