Java Web应用下载文件以及下…

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;
}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值