文章简介
- 客户端(用户)下载文件
参考:点这文章链接 - 服务端下载
客户端(用户)下载文件
注意:
-
通过流方式输出。
-
为了弹出下载框必设置 response.setHeader()
-
为了输出是pdf文件,需设置:response.setContentType(“application/pdf”);
-
如果文件名是中文需设置String name = URLEncoder.encode(fileName, “UTF-8”);
这里以OutputStream输出pdf下载为例:
package com.kingworks.local.service;
import com.kingworks.common.redis.Redis_Common;
import com.kingworks.common.redis.Redis_Return;
import com.kingworks.common.util.CommonUtil;
import com.kingworks.common.util.Session;
import net.sf.json.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.Map;
/****************************************
* @name GMCCAPP_704_001_001_001
* @description 电子发票的下载
* @author ZhangRuiguang
* @since 2019-10-24
***************************************/
public class GMCCAPP_704_001_001_001 extends BaseServiceBean implements BaseService{
public JSONObject handle(JSONObject reqJson) {
JSONObject respJson = new JSONObject();
String result = "001";
String desc = "系统繁忙";
boolean isGone = true;
Session session = null;
Map<String, String> channelMap = null;
try {
session = (Session) CommonUtil.localThread.get();
channelMap = session.getChannelMap();
HttpServletResponse response = session.getResponse();
String applyoid = reqJson.getString("applyoid");
if (org.apache.commons.lang.StringUtils.isEmpty(applyoid) ) {
isGone = false;
channelMap.put("errorPlatform", "LOCAL");
channelMap.put("errorCode", "001");
channelMap.put("errorInfo", "applyoid为空");
}
String pdfResult = "";
if (isGone) {
// 查询缓存数据
Redis_Return redis_Return = Redis_Common.getRedisReturn("INVOICE_"+applyoid);
if("000".equals(redis_Return.getRetCode())){
pdfResult = (String)redis_Return.getRetObj();
if (StringUtils.isNotEmpty(pdfResult)) {
byte[] pdfResults= Base64.decodeBase64(pdfResult);
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment; filename="+new String( ("INVOICE" + ".pdf").getBytes(),
"iso-8859-1"));
OutputStream os = response.getOutputStream();
os.write(pdfResults);
os.flush();
os.close();
result = "000";
desc = "下载成功";
} else {
result = "111";
desc = "文件链接已过期";
}
}
}
} catch (Exception e) {
channelMap.put("errorPlatform", "LOCAL");
channelMap.put("errorCode", "001");
channelMap.put("errorInfo", CommonUtil.getExceptionInfo(e));
}
session.setChannelMap(channelMap);
respJson.put("result", result);
respJson.put("desc", desc);
return respJson;
}
}
在此提醒:在线预览还是下载区别只在于输出时我们设置是预览还是下载,如果同时要,则需定义一个标识即可,如:
//预览还是下载
if(flag == null){
response.setHeader("Content-Disposition", "inline;filename="+name);
}else{
response.setHeader("Content-Disposition", "attachment;filename="+name);
}