header中Content-Disposition的作用 用于浏览器不打开图片直接下载

今天查看Struts2的文件上传部分 发现有个例子开头打印的信息中有Content-Disposition,一时好奇,所以了解了一下。顺便学习一下文件上传所需要的注意事项。

      Content-disposition 是 MIME 协议的扩展,MIME 协议指示 MIME 用户代理如何显示附加的文件。当 Internet Explorer 接收到头时,它会激活文件下载对话框,它的文件名框自动填充了头中指定的文件名。(请注意,这是设计导致的;无法使用此功能将文档保存到用户的计算机上,而不向用户询问保存位置。)   

        服务端向客户端游览器发送文件时,如果是浏览器支持的文件类型,一般会默认使用浏览器打开,比如txt、jpg等,会直接在浏览器中显示,如果需要提示用户保存,就要利用Content-Disposition进行一下处理,关键在于一定要加上attachment:

Response.AppendHeader("Content-Disposition","attachment;filename=FileName.txt");

备注:这样浏览器会提示保存还是打开,即使选择打开,也会使用相关联的程序比如记事本打开,而不是IE直接打开了。

Content-Disposition就是当用户想把请求所得的内容存为一个文件的时候提供一个默认的文件名。具体的定义如下:

content-disposition = “Content-Disposition” “:”

disposition-type *( “;” disposition-parm )

disposition-type = “attachment” | disp-extension-token

disposition-parm = filename-parm | disp-extension-parm

filename-parm = “filename” “=” quoted-string

disp-extension-token = token

disp-extension-parm = token “=” ( token | quoted-string )

那么由上可知具体的例子:

Content-Disposition: attachment; filename=“filename.xls”

       当然filename参数可以包含路径信息,但User-Agnet会忽略掉这些信息,只会把路径信息的最后一部分做为文件名。当你在响应类型为application/octet- stream情况下使用了这个头信息的话,那就意味着你不想直接显示内容,而是弹出一个”文件下载”的对话框,接下来就是由你来决定“打开”还是“保存” 了。

注意事项:

1.当代码里面使用Content-Disposition来确保浏览器弹出下载对话框的时候。 response.addHeader("Content-Disposition","attachment");一定要确保没有做过关于禁止浏览器缓存的操作。如下:

response.setHeader("Pragma", "No-cache"); 
response.setHeader("Cache-Control", "No-cache"); 
response.setDateHeader("Expires", 0);

不然会发现下载功能在operafirefox里面好好的没问题,在IE下面就是不行,就是找不到文件。

//struts   框架处理:

1 配置文件:

<!-- 下载附件 -->
<action name="downloadAttachment" method="downloadAttachment" class="attAction">
<!--配置结果类型为stream的结果-->
   <result name="success" type="stream">
      <!--指定下载文件的文件类型-->
         <param name="contentType"></param>
      <!--指定下载文件的文件位置-->
         <param name="inputName">targetFile</param>
      <!--指定下载文件的下载方式及下载时的保存文件名,filename保存时的文件名必须有扩展名,扩展名指示了下载类型的图标-->
         <param name="contentDisposition">contentDisposition</param>
      <!--指定下载文件的缓冲区大小-->
         <param name="bufferSize">40960</param>
   </result>
   <result name="input">/web/systemCenter/att/errorMessage.jsp</result>
</action>


<!-- 删除附件 -->
<action name="delAttachment" method="delAttachment" class="attAction" />


<!-- 附件预览 -->
<action name="previewAttachment" method="previewAttachment" class="attAction">
<result name="success">/web/systemCenter/att/attPreview.jsp</result>
</action>

2 java 代码:

package com.mx.travel.my.action;


import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;


import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.mx.travel.util.AppPath;
import org.mx.travel.util.BaseUtil;
import org.mx.travel.util.WSUtil;


import com.alibaba.fastjson.JSON;
import com.mx.travel.base.action.BaseAction;
import com.mx.travel.my.att.api.helper.AttachmentConfigHelper;
import com.mx.travel.my.att.api.helper.AttachmentHelper;
import com.mx.travel.my.att.api.helper.AttachmentUserHelper;
import com.mx.travel.my.att.pojo.Attachment;
import com.mx.travel.my.att.pojo.AttachmentConfig;
import com.mx.travel.my.system.api.helper.CodeHelper;
import com.mx.travel.my.util.JsonToObject;
import com.mx.travel.util.DESSecurity;
import com.mx.travel.util.FileUtil;
import com.mx.travel.util.ListUtil;
import com.mx.travel.util.Page;
import com.mx.travel.util.SystemConfig;
import com.mx.travel.util.Util;
import com.opensymphony.xwork2.ActionContext;


@SuppressWarnings("serial")
public class AttachmentAction extends BaseAction {

private static Logger logger = Logger.getLogger(AttachmentAction.class); 

private Integer attId;
private String attIdStr;
private String attIdDES;//加密过的附件id
private Integer acId;
private String attCode;
private String pkValue;
private String[] title;
private String attPath;
private String[] note;
private String empCode;
private String empName;
private String createTime;
private int isOpen;
private int isEnable;

private String acCode;
private String fileExt;
private Integer fileSize;
private Integer checkedAttConfigId;

private int isDelete;
private int isOne;
private int isBatch;

String schCode;
String schName;
String schIsEnable;


Integer schAcId;
String schAttCode;
String schPkValue;
String schTitle;
String schEmpCode;
String schEmpName;

private String msg;//下载文件提示信息

//private String pojoName = "Attachment";
//private String pojoDesc = "附件管理";

public static String attDrivePath = AppPath.fileHostUrl;
private InputStream targetFile;//指定下载文件的文件流
private String contentDisposition;//指定下载文件的下载方式及下载时的保存文件名,filename保存时的文件名必须有扩展名,扩展名指示了下载类型的图标

/**
* 添加附件的附件列表
* @return
* @author  liuyandong
* @date 创建时间:2015-12-26 下午5:00:03 
* @version 1.0
*/
public String loadAttList() {
String hql = " from Attachment a where a.attachmentConfig.acCode = '"+acCode+"' and a.pkValue = '"+pkValue+"' ";
List<Attachment> attList = searchAttachmentList(hql);
//附件路径修改(upload/my/user/photo/2015/12/a.jpg 改为 a.jpg)
if (attList != null &&  attList.size() > 0) {
for (Attachment attachment : attList) {
if (attachment.getIsOpen() == 1) {//公开后不用判断权限表
attachment.setAuth(true);
} else {//不公开则检测权限表
int attId = attachment.getAttId();
String resultJson = AttachmentUserHelper.isExistData(attId, getSysSession().getUser().getEmpCode());
if (WSUtil.isSuccess(resultJson)) {
String dataStr = WSUtil.getResultData(resultJson);
attachment.setAuth(Boolean.valueOf(dataStr));
} else {//验证是否有权限失败,设置没有权限
attachment.setAuth(false);
}
}
//附件名称修改(某某某一寸照片 改为 某某某一寸照片.jpg)
String attPath = attachment.getAttPath();
String title = attachment.getTitle() + "." + Util.getFileExt(attPath);
attachment.setTitle(title);
}
}


setRequestAttribute("list", attList);
setRequestAttribute("schIsEnable", ListUtil.createSelectByIsEnable("schIsEnable", "schIsEnable", "账号状态", schIsEnable, null, null));
setRequestAttribute("pkValue", pkValue);
setRequestAttribute("acCode", acCode);
setRequestAttribute("msg", msg);
return SUCCESS;
}
/**
* 查看附件的附件列表
* @return
* @author  liuyandong
* @date 创建时间:2015-12-26 下午5:01:02 
* @version 1.0
*/
public String loadAttListSearch() {
String hql = " from Attachment a ";

String  whereStr = "";
if (!Util.isEqual(acCode)) {
whereStr += " and a.attachmentConfig.acCode = '"+acCode+"' ";
}
if (!Util.isEqual(pkValue)) {
whereStr += " and a.pkValue = '"+pkValue+"' ";
}
if(whereStr.length()>0){
hql += " where 1=1 and a.isEnable=1 " + whereStr;
}else{//不允许两个查询条件都为空,
hql += " where 1=2 ";
}

List<Attachment> attList = searchAttachmentList(hql);
if (attList != null && attList.size() > 0) {
//StringBuffer attIdStr = new StringBuffer("");
for (Attachment attachment : attList) {
if (attachment.getIsOpen() == 1) {//公开后不用判断权限表
attachment.setAuth(true);
} else {//不公开则检测权限表
int attId = attachment.getAttId();
String resultJson = AttachmentUserHelper.isExistData(attId, getSysSession().getUser().getEmpCode());
if (WSUtil.isSuccess(resultJson)) {
String dataStr = WSUtil.getResultData(resultJson);
attachment.setAuth(Boolean.valueOf(dataStr));
} else {//验证是否有权限失败,设置没有权限
attachment.setAuth(false);
}
}
//附件路径修改(upload/my/user/photo/2015/12/a.jpg 改为 a.jpg)
String attPath = attachment.getAttPath();
int beginIndex = attPath.lastIndexOf("/") + 1;
attPath = attPath.substring(beginIndex);
attachment.setAttPath(attPath);

//附件名称修改(某某某一寸照片 改为 某某某一寸照片.jpg)
String title = attachment.getTitle() + "." + Util.getFileExt(attPath);
attachment.setTitle(title);
}
}
setRequestAttribute("list", attList);
setRequestAttribute("acCode", acCode);
setRequestAttribute("schPkValue", schPkValue);
setRequestAttribute("pkValue", pkValue);
return SUCCESS;
}
/**
* 加载菜单下的【附件列表】
* @return
* @author  liuyandong
* @date 创建时间:2015-12-26 上午11:26:21 
* @version 1.0
*/
public String loadModuleAttList() {
String hql = " from Attachment a where 1=1 ";
List<Attachment> attList = searchAttachmentList(hql);


//方案下拉列表
String configJson = AttachmentConfigHelper.getAllList();
List attConfigList = JsonToObject.JsonToAttConfigList(configJson);
setRequestAttribute("attConfigList", ListUtil.createSelect(attConfigList, "schAcId", "schAcId", "请选择方案", schAcId==null?null:schAcId.toString(), new String[] { }, new String[] { }));
//setRequestAttribute("attConfigList", ListUtil.createSelect(attConfigList, "acCode", "acCode", "请选择方案", "acCode", "title", acId==null?null:acId.toString(), new String[] { }, new String[] { }));
setRequestAttribute("list", attList);
return SUCCESS;
}
/**
* 查询附件列表
* @author  liuyandong
* @date 创建时间:2015-12-26 下午5:12:36 
* @version 1.0
*/
private List<Attachment> searchAttachmentList(String hql) {
if (!Util.isEqual(schAcId)) {
hql += " and a.attachmentConfig.acId = '"+schAcId+"' ";
}
if (!Util.isEqual(schAttCode)) {
hql += " and a.attCode = '"+schAttCode+"' ";
}
if (!Util.isEqual(schPkValue)) {
hql += " and a.pkValue = '"+schPkValue+"' ";
}
if (!Util.isEqual(schTitle)) {
hql += " and a.title like '%"+schTitle+"%' ";
}
if (!Util.isEqual(schEmpCode)) {
hql += " and a.empCode = '"+schEmpCode+"' ";
}
if (!Util.isEqual(schEmpName)) {
hql += " and a.empName like '%"+schEmpName+"%' ";
}
Page page = new Page(getActionName(), getQueryString());
if (page.isFirstLoad()) {
page.setSearchKeys("schAcId", schAcId);
page.setSearchKeys("schAttCode", schAttCode);
page.setSearchKeys("schPkValue", schPkValue);
page.setSearchKeys("schTitle", schTitle);
page.setSearchKeys("schEmpCode", schEmpCode);
page.setSearchKeys("schEmpName", schEmpName);


page.setSearchKeys("acCode", acCode);
page.setSearchKeys("pkValue", pkValue);
String jsonAttListCount = AttachmentHelper.getDataCount(" select count(attId) "+hql);

if (WSUtil.isSuccess(jsonAttListCount)) { 
page.setItemCount(Integer.valueOf(WSUtil.getResultData(jsonAttListCount)));
} else {
page.setItemCount(0);
}
}
String jsonAttPageList = AttachmentHelper.getListByPage(hql , page.getStartNo(), page.getPageSize());
List<Attachment> list = null;
if (WSUtil.isSuccess(jsonAttPageList)) {
list = JsonToObject.JsonToAttachmentList(jsonAttPageList);
// setRequestAttribute("list", list);
}
setRequestAttribute(Page.PAGE_INFO, page.getPageInfo());
return list;
}

/**
* 查询附件列表(公共没有查询条件)
* 查询出的都是启用状态的
* @author  tianwei
* @date 创建时间:2016-5-31
* @version 1.0
*/
public String loadAttListPop() {
String hql = " from Attachment a where isEnable=1 and a.attachmentConfig.acCode = '"+acCode+"' and a.pkValue = '"+pkValue+"' ";
List<Attachment> attList = searchAttachmentList(hql);
//附件路径修改(upload/my/user/photo/2015/12/a.jpg 改为 a.jpg)
if (attList != null &&  attList.size() > 0) {
for (Attachment attachment : attList) {
if (attachment.getIsOpen() == 1) {//公开后不用判断权限表
attachment.setAuth(true);
} else {//不公开则检测权限表
int attId = attachment.getAttId();
String resultJson = AttachmentUserHelper.isExistData(attId, getSysSession().getUser().getEmpCode());
if (WSUtil.isSuccess(resultJson)) {
String dataStr = WSUtil.getResultData(resultJson);
attachment.setAuth(Boolean.valueOf(dataStr));
} else {//验证是否有权限失败,设置没有权限
attachment.setAuth(false);
}
}
//附件名称修改(某某某一寸照片 改为 某某某一寸照片.jpg)
String attPath = attachment.getAttPath();
String title = attachment.getTitle() + "." + Util.getFileExt(attPath);
attachment.setTitle(title);
}
}
setRequestAttribute("list", attList);
setRequestAttribute("pkValue", pkValue);
setRequestAttribute("acCode", acCode);
//setRequestAttribute("msg", msg);
return SUCCESS;
}

// 加载添加
@SuppressWarnings({ "rawtypes", "unchecked" })
public String loadAddAtt() {
AttachmentConfig attConfig = null;
String resultJson = AttachmentConfigHelper.getByCode(acCode);
if (WSUtil.isSuccess(resultJson)) {
String data = WSUtil.getResultData(resultJson);
if (!Util.isEqual(data)) {
attConfig = JSON.parseObject(data,AttachmentConfig.class);
setRequestAttribute("category", attConfig.getCategory());
setRequestAttribute("dirName", attConfig.getDirName());
setRequestAttribute("fileExt", attConfig.getFileExt());
setRequestAttribute("fileSize", attConfig.getFileSize());
setRequestAttribute("showFileSize", attConfig.getFileSize()+"KB");
setRequestAttribute("title", attConfig.getTitle());
}
}
setRequestAttribute("acCode", acCode);
setRequestAttribute("pkValue", pkValue);
setRequestAttribute("isDelete", isDelete);
setRequestAttribute("isOne", isOne);
setRequestAttribute("isBatch", isBatch);
return SUCCESS;
}


@SuppressWarnings("unused")
public void addAttachment() {
String msg = "";
String checkMsg = "";
String result = "";
String successStr = "";//记录上传成功的附件编码,用于写系统日志
String failStr = "";//记录保存失败的附件标题
int sNum =0;//统计上传成功的附件个数,用于写系统日志
boolean check = true;


AttachmentConfig attachmentConfig = null;
String resultJson = AttachmentConfigHelper.getByCode(acCode);
if (WSUtil.isSuccess(resultJson)) {
String data = WSUtil.getResultData(resultJson);
if (!Util.isEqual(data)) {
attachmentConfig = JSON.parseObject(data,AttachmentConfig.class);
if(file != null && file.length>0){
//检查上传文件的类型和大小是否合法,文件标题是否字数超限↓
for (int i = 0; i < file.length; i++) {
//获取上传文件的类型
String fn = BaseUtil.getFileName(fileFileName[i]);
String fe = BaseUtil.getFileExt(fn);
// 是否允许上传该类型
String tmp = attachmentConfig.getFileExt();
Pattern p = Pattern.compile(fe);
Matcher m = p.matcher(tmp);
if (!m.find()) {//文件类型不合法
check = false;
break;
}
long myFileSize = file[i].length();
int allowMaxSize = attachmentConfig.getFileSize() * 1024;
if (myFileSize > allowMaxSize) {//文件大小不合法
check = false;
break;
}
if (title != null && title.length > 0 && title[i] != null) {
String myTitle = title[i];
if (myTitle.length() > 100) {//文件标题字数超限
check = false;
break;
}
}
}
//检查上传文件的类型和大小是否合法,文件标题是否字数超限↑
if (check) {
//上传文件和保存数据
for (int i = 0; i < file.length; i++) {
try {
String newAttCode = CodeHelper.getCode("SYS_CODE_RULE_ATTACHMENT");
String[] uploadResult = uploadAttFile(SystemConfig.get("UPLOAD_PATH_ROOT"), attPath, i, newAttCode);
if (!Util.isEqual(uploadResult) && !Util.isEqual(uploadResult[0]) ) {
if(uploadResult[0].equals("0")){
logger.error("上传第"+i+1+"个附件失败! 文件名:"+fileFileName[i]);
//System.out.println("上传第"+i+1+"个附件失败! 文件名:"+fileFileName[i]);
if(Util.isEqual(failStr)) {
failStr += fileFileName[i];
} else{ 
failStr += ","+fileFileName[i]; 
}
}else{
if (pkValue != null && pkValue.length() > 0) {
if (pkValue.contains(",")) {//多条数据批量上传附件
String[] pkValueArray = pkValue.split("\\,");
int num = 1;
for (String pk : pkValueArray) {
//删除文件和删除数据
delAttDataAndFile(attachmentConfig.getAcCode(), pk);
//保存数据
String code = newAttCode + "_" + num;
Attachment att = new Attachment();
att.setAttachmentConfig(attachmentConfig);
att.setAttPath(uploadResult[1]);//uploadResult[1]上传文件路径
att.setAttCode(code);
att.setEmpCode(getSysSession().getUser().getEmpCode());
att.setEmpName(getSysSession().getUser().getEmpName());
att.setCreateTime(Util.getCurrentTimestamp());
att.setPkValue(pk);
if(Util.isEqual(title[i])){
title[i] = code;
}
title[i] = FileUtil.replaceSpecificSymbol(title[i]);
att.setTitle(title[i]);
att.setNote(note[i]);
att.setIsEnable(Integer.valueOf("1"));
att.setIsOpen(Integer.valueOf("1"));
int attId = JsonToObject.JsonToInt(AttachmentHelper.addData(JSON.toJSONString(att)));
if(attId>0){
if(Util.isEqual(successStr)) {
successStr += newAttCode;
} else{ 
successStr += ","+newAttCode; 
}
} else {
if(Util.isEqual(failStr)) {
failStr += fileFileName[i];
} else{ 
failStr += ","+fileFileName[i]; 
}
}
num = num + 1;
}
} else {
Attachment att = new Attachment();
att.setAttachmentConfig(attachmentConfig);
att.setAttPath(uploadResult[1]);//uploadResult[1]上传文件路径
att.setAttCode(newAttCode);
att.setEmpCode(getSysSession().getUser().getEmpCode());
att.setEmpName(getSysSession().getUser().getEmpName());
att.setCreateTime(Util.getCurrentTimestamp());
att.setPkValue(pkValue);
if(Util.isEqual(title[i])){
title[i] = newAttCode;
}
title[i] = FileUtil.replaceSpecificSymbol(title[i]);
att.setTitle(title[i]);
att.setNote(note[i]);
att.setIsEnable(Integer.valueOf("1"));
att.setIsOpen(Integer.valueOf("1"));
int attId = JsonToObject.JsonToInt(AttachmentHelper.addData(JSON.toJSONString(att)));
if(attId>0){
if(Util.isEqual(successStr)) {
successStr += newAttCode;
} else{ 
successStr += ","+newAttCode; 
}
} else {
if(Util.isEqual(failStr)) {
failStr += fileFileName[i];
} else{ 
failStr += ","+fileFileName[i]; 
}
}
}
}
}
}else{
logger.error("上传第"+i+1+"个附件失败! 文件名:"+fileFileName[i]);
//System.out.println("上传第"+i+1+"个附件失败! 文件名:"+fileFileName[i]);
if(Util.isEqual(failStr)) {
failStr += fileFileName[i];
} else{ 
failStr += ","+fileFileName[i]; 
}
}
} catch (Exception e) {
e.printStackTrace();
logger.error("上传第"+i+1+"个附件失败! 文件名:"+fileFileName[i]);
//System.out.println("上传第"+i+1+"个附件失败! 文件名:"+fileFileName[i]);
if(Util.isEqual(failStr)) {
failStr += fileFileName[i];
} else{ 
failStr += ","+fileFileName[i]; 
}
}
}
if (!Util.isEqual(failStr)) {
msg = "文件名为【" + failStr + "】的附件保存失败!";
}
} else {
msg = "验证不通过,请检查文件的类型、大小是否符合要求,文件标题是否字数超限";
}
} else {
msg = "没有需要上传的文件!";
}
//if(!Util.isEqual(successStr)){
//LogHelper.writeLog(1, successStr, 1, "操作员:" + getSysSession().getUser().getEmpName() + " 上传了["+attachmentConfig.getTitle()+"] , "+sNum+"个附件:" + successStr+" ,原数据表的主键:"+pkValue, 1, pojoName, pojoDesc, getSysSession().getUser()
// .getEmpCode(), getSysSession().getUser().getEmpName(), SystemConfig.currSysCode, SystemConfig.currSysName);
//}
} else {
msg = "方案编码为【" + acCode + "】的方案不存在!";
}
} else {
msg = "方案编码为【" + acCode + "】的方案不存在!";
}
setRequestAttribute("pkValue", pkValue);
setRequestAttribute("acCode", acCode);
String returnMsg = "{\"code\":\"0\",\"message\":\"上传成功!\"}";
if (!Util.isEqual(msg)) {
logger.error(msg);
returnMsg = "{\"code\":\"-1\",\"message\":\"" + msg + "\"}";
}
printContent(returnMsg);
}
/*
* 删除附件数据库数据和文件数据
* @param acCode 方案编码
* @param pkValue 主键值
*/
private void delAttDataAndFile(String acCode, String pkValue) {
//1.查询是否存在指定方案编码、指定主键值的附件数据
String attJson = AttachmentHelper.getListByAccodePkValue(acCode, pkValue);
List<Attachment> attList = null;
if (WSUtil.isSuccess(attJson)) {
attList = JsonToObject.JsonToAttachmentList(attJson);
}
//2.从附件数据中拿出附件路径。如果附件数据是一条或多条,需要循环查询对应的附件路径是否有被其他数据使用
// 如果,未被使用,该条数据删除,附件文件删除;如果,已被使用,该条数据删除,文件不删除
if (attList != null && attList.size() > 0) {
for (Attachment attachment : attList) {
String attPath = attachment.getAttPath();
String resultJson = AttachmentHelper.deleteDataById(attachment.getAttId(), attPath,getSysSession().getUser().getEmpCode(),getSysSession().getUser().getEmpName());
if (WSUtil.isSuccess(resultJson)) {
int data = Integer.parseInt(WSUtil.getResultData(resultJson));
if (data < 2) {
String path = attDrivePath+"/"+ attPath;
FileUtil.delFile(path);
}
}
}
}
}

/**
* 上传文件
* @param basePath
* @param uploadPath
* @param fileIndex
* @param fileName
* @return 返回数组,[0]:上传结果,0(上传失败);[1]:上传文件路径
* @author  chenlili
* @date 创建时间:2015-12-25 下午3:02:52 
* @version 1.0
*/
public String[] uploadAttFile(String basePath,String uploadPath,Integer fileIndex,String fileName) {

String uploadMsg[] = new String[2];
uploadMsg[0] = "0";
try {
String uploadPathUrl = basePath + "/" + uploadPath + "/" + BaseUtil.getYearValue() + "/" + BaseUtil.getMonthValue();
String serverFilePath = attDrivePath + uploadPathUrl;

String fn = BaseUtil.getFileName(fileFileName[fileIndex]);;
String fe = BaseUtil.getFileExt(fn);
String fnNew = fileName + "." + fe;


File uploadFile = new File(serverFilePath); // 把命名好的文件上传到指定的路径
if (!uploadFile.exists()) {
uploadFile.mkdirs(); // 创建该目录
}
InputStream in = new FileInputStream(file[fileIndex]);
OutputStream out = new FileOutputStream(uploadFile + "\\" + fnNew); // 写入流

byte[] buffer = new byte[5 * 1024 * 1024];// 5M
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.close();
uploadMsg[0] = "1";//成功上传标识
uploadMsg[1] = uploadPathUrl.replace("\\", "/") + "/" + fnNew;
logger.info("上传了文件:" + uploadMsg[1]);
//System.out.println("文件为:" + uploadMsg[1]);
} catch (FileNotFoundException e) {
uploadMsg[1] = e.getMessage();
e.printStackTrace();
} catch (IOException e) {
uploadMsg[1] = e.getMessage();
e.printStackTrace();
}
return uploadMsg;
}


/**
* 启用
* @return
* @throws Exception String 
* @author chenlili
* 创建时间:2015-12-16 下午4:12:38
*/
public void enableAtt() {
if (attIdStr.length() > 0 && attIdStr.contains(",")) {
String[] attIdArray = attIdStr.split("\\,");
for (String attId : attIdArray) {
enAtt(attId);
}
} else {
enAtt(attIdStr);
}
}
private void enAtt(String attId) {
String resultJson = AttachmentHelper.getDataById(Integer.parseInt(attId));
Attachment att = JsonToObject.JsonToAttachment(resultJson);
att.setIsEnable(1);
String note ="启用了";
//String msgJson = 
AttachmentHelper.updateData(JSON.toJSONString(att),getSysSession().getUser().getEmpCode(),getSysSession().getUser().getEmpName(),note);
/*if (WSUtil.isSuccess(msgJson)) {
LogHelper.writeLog(1, attId.toString(), 2, "操作员:" + getSysSession().getUser().getEmpName() + " 启用了附件:" + attId, 1, pojoName, pojoDesc, getSysSession().getUser().getEmpCode(),
getSysSession().getUser().getEmpName(), SystemConfig.currSysCode, SystemConfig.currSysName);
}*/
}


/**
* 禁用
* @return
* @throws Exception String 
* @author chenlili
* 创建时间:2015-12-16 下午4:12:54
*/
public void disableAtt() {
if (attIdStr.length() > 0 && attIdStr.contains(",")) {
String[] attIdArray = attIdStr.split("\\,");
for (String attId : attIdArray) {
disAtt(attId);
}
} else {
disAtt(attIdStr);
}
}
private void disAtt(String attId) {
String resultJson = AttachmentHelper.getDataById(Integer.parseInt(attId));
Attachment att = JsonToObject.JsonToAttachment(resultJson);
att.setIsEnable(0);
String note ="禁用了";
//String msgJson = 
AttachmentHelper.updateData(JSON.toJSONString(att),getSysSession().getUser().getEmpCode(),getSysSession().getUser().getEmpName(),note);
/*if (WSUtil.isSuccess(msgJson)) {
LogHelper.writeLog(1, attId.toString(), 2, "操作员:" + getSysSession().getUser().getEmpName() + " 禁用了附件:" + attId, 1, pojoName, pojoDesc, getSysSession().getUser().getEmpCode(),
getSysSession().getUser().getEmpName(), SystemConfig.currSysCode, SystemConfig.currSysName);
}*/
}
/**
* 公开
* @author  liuyandong
* @date 创建时间:2016-1-12 上午10:15:44 
* @version 1.0
*/
public void openAtt() {
if (attIdStr.length() > 0 && attIdStr.contains(",")) {
String[] attIdArray = attIdStr.split("\\,");
for (String attId : attIdArray) {
openAtt(attId);
}
} else {
openAtt(attIdStr);
}
}
private void openAtt(String attId) {
String resultJson = AttachmentHelper.getDataById(Integer.parseInt(attId));
Attachment att = JsonToObject.JsonToAttachment(resultJson);
att.setIsOpen(1);
String note ="公开了";
AttachmentHelper.updateData(JSON.toJSONString(att),getSysSession().getUser().getEmpCode(),getSysSession().getUser().getEmpName(),note);
}


/**
* 关闭
* @author  liuyandong
* @date 创建时间:2016-1-12 上午10:15:44 
* @version 1.0
*/
public void closeAtt() {
if (attIdStr.length() > 0 && attIdStr.contains(",")) {
String[] attIdArray = attIdStr.split("\\,");
for (String attId : attIdArray) {
closeAtt(attId);
}
} else {
closeAtt(attIdStr);
}
}
private void closeAtt(String attId) {
String resultJson = AttachmentHelper.getDataById(Integer.parseInt(attId));
Attachment att = JsonToObject.JsonToAttachment(resultJson);
att.setIsOpen(0);
String note ="关闭了";
AttachmentHelper.updateData(JSON.toJSONString(att),getSysSession().getUser().getEmpCode(),getSysSession().getUser().getEmpName(),note);
}


/**
* 下载附件
* msg不同值代表的意思
* file_not_found:系统找不到指定的文件!!!
* error:下载文件失败!!!
* check_auth_not_pass:验证权限不通过
* check_auth_error:验证权限失败
* database_no_data:数据库没有该文件信息
* @author  liuyandong
* @date 创建时间:2015-12-28 下午4:18:33 
* @version 1.0
*/
public String downloadAttachment() {
setRequestAttribute("acCode", acCode);
setRequestAttribute("pkValue", pkValue);
//参数解密开始
if (Util.isEqual(attIdDES)) {
setRequestAttribute("msg", "database_no_data");
return INPUT;
} else {
attIdDES = new DESSecurity().fileDownDecrypt(attIdDES);
if (Util.isEqual(attIdDES)) {
setRequestAttribute("msg", "error");
return INPUT;
} else {
attId = Integer.parseInt(attIdDES);
}
}
//参数解密结束
//isOpen不可以直接从页面传过来,否则用户直接在地址栏传参isOpen=1,则会跳过权限验证
String json = AttachmentHelper.getDataById(attId);
Attachment attment = JsonToObject.JsonToAttachment(json);
if (!Util.isEqual(attment)) {
if (attment.getIsOpen() != 1) {//不公开
String resJson = AttachmentUserHelper.isExistData(attId, getSysSession().getUser().getEmpCode());
if (WSUtil.isSuccess(resJson)) {
String dataStr = WSUtil.getResultData(resJson);
if (!Boolean.valueOf(dataStr)) {//验证权限不通过
setRequestAttribute("msg", "check_auth_not_pass");
return INPUT;
}
} else {//验证权限失败
setRequestAttribute("msg", "check_auth_error");
return INPUT;
}
}
String attPath = attDrivePath+"/"+ attment.getAttPath();
//设置contentDisposition开始
String fileType = attPath.substring(attPath.lastIndexOf("."));//文件后缀名
String title = attment.getTitle();
title = FileUtil.replaceSpecificSymbol(title);//特殊字符替换
title += fileType;
HttpServletRequest request = ServletActionContext.getRequest();
String userAgent = request.getHeader("User-Agent");
byte[] titleBytes;
try {
titleBytes = userAgent.contains("MSIE")?title.getBytes():title.getBytes("utf-8");
title = new String(titleBytes, "ISO8859-1" );
} catch (UnsupportedEncodingException e1) {

}
contentDisposition = String.format("attachment;filename=\"%s\"", title);
//设置contentDisposition结束
try {
//下载文件的文件流
targetFile = new BufferedInputStream(new FileInputStream(attPath));
return SUCCESS;
} catch (Exception e) {
setRequestAttribute("msg", "file_not_found");
return INPUT;
}
} else {
setRequestAttribute("msg", "database_no_data");
return INPUT;
}
}


/**
* 预览附件
* @return
* @author  liuyandong
* @date 创建时间:2016-9-2 下午4:45:14 
* @version 1.0
*/
public String previewAttachment() {
//参数解密开始
if (Util.isEqual(attIdDES)) {
setRequestAttribute("msg", "database_no_data");
return SUCCESS;
} else {
attIdDES = new DESSecurity().fileDownDecrypt(attIdDES);
if (Util.isEqual(attIdDES)) {
setRequestAttribute("msg", "error");
return SUCCESS;
} else {
attId = Integer.parseInt(attIdDES);
}
}
//参数解密结束
//isOpen不可以直接从页面传过来,否则用户直接在地址栏传参isOpen=1,则会跳过权限验证
String json = AttachmentHelper.getDataById(attId);
Attachment attment = JsonToObject.JsonToAttachment(json);
if (!Util.isEqual(attment)) {
       //附件服务器文件路径
String attPath = attDrivePath+"/"+ attment.getAttPath();
File fromFile = new File(attPath);
if (!fromFile.exists()) {// 判断文件是否存在  
setRequestAttribute("msg", "file_not_found");
return SUCCESS;
}

if (attment.getIsOpen() != 1) {//不公开
String resJson = AttachmentUserHelper.isExistData(attId, getSysSession().getUser().getEmpCode());
if (WSUtil.isSuccess(resJson)) {
String dataStr = WSUtil.getResultData(resJson);
if (!Boolean.valueOf(dataStr)) {//验证权限不通过
setRequestAttribute("msg", "check_auth_not_pass");
return SUCCESS;
}
} else {//验证权限失败
setRequestAttribute("msg", "check_auth_error");
return SUCCESS;
}
}
//项目根目录
ActionContext ac = ActionContext.getContext();
       ServletContext sc = (ServletContext) ac.get(ServletActionContext.SERVLET_CONTEXT);
       String path = sc.getRealPath("/");


       //项目根目录下的文件路径
String filePath = path + "images_temp/" + attment.getAttPath();
File toFile = new File(filePath);


//复制文件到项目根目录下
FileUtil.copyFile(toFile, fromFile);
setRequestAttribute("filePath", "images_temp/" + attment.getAttPath());
return SUCCESS;
} else {
setRequestAttribute("msg", "database_no_data");
return SUCCESS;
}
}


/**
* 删除附件
* @author  liuyandong
* @date 创建时间:2015-12-29 下午6:00:56 
* @version 1.0
*/
public void delAttachment() {
boolean result = true;
StringBuffer errorAttId = new StringBuffer("");
if (attIdStr.length() > 0) {
if (attIdStr.contains(",")) {
String[] attIdArray = attIdStr.split("\\,");
for (String attId : attIdArray) {
Attachment att = JsonToObject.JsonToAttachment(AttachmentHelper.getDataById(Integer.parseInt(attId)));
String attPath = attDrivePath+"/"+ att.getAttPath();
String resultJson = AttachmentHelper.deleteDataById(Integer.parseInt(attId), attPath,getSysSession().getUser().getEmpCode(),getSysSession().getUser().getEmpName());
if (WSUtil.isSuccess(resultJson)) {
int data = Integer.parseInt(WSUtil.getResultData(resultJson));
if (data < 2) {
FileUtil.delFile(attPath);
}
}
if (WSUtil.isError(resultJson)) {
result = false;
if (errorAttId != null && errorAttId.length() > 0) {
errorAttId.append(",");
}
errorAttId.append(attId);
}
}
} else {
Attachment att = JsonToObject.JsonToAttachment(AttachmentHelper.getDataById(Integer.parseInt(attIdStr)));
String attPath = attDrivePath+"/"+ att.getAttPath();
String resultJson = AttachmentHelper.deleteDataById(Integer.parseInt(attIdStr), attPath,getSysSession().getUser().getEmpCode(),getSysSession().getUser().getEmpName());
if (WSUtil.isSuccess(resultJson)) {
int data = Integer.parseInt(WSUtil.getResultData(resultJson));
if (data < 2) {
FileUtil.delFile(attPath);
}
}
if (WSUtil.isError(resultJson)) {
result = false;
if (errorAttId != null && errorAttId.length() > 0) {
errorAttId.append(",");
}
errorAttId.append(attId);
}
}

}


if (result) {
printContent("{\"code\":\"0\",\"message\":\"删除成功!\"}");
} else {
String msg = "附件Id为" + errorAttId.toString() + "的附件删除失败!";
printContent("{\"code\":\"-1\",\"message\":\"" + msg + "\"}");
}
}
/**
* 首页的公司表格下载按钮,刚开始点击的不验证的action
* @return
* @author  tianwei
* @date 创建时间:2016-7-7 上午9:42:39 
* @version 1.0
*/
public String loadAttListUnCheck(){
Integer userId = getSysSession().getUser().getUserId();
boolean result = SystemConfig.checkAction(userId, "loadStruFormList");
if (!result) {
return "findList";
} else {
return "adminList";
}
}


public String getAcCode() {
return acCode;
}


public void setAcCode(String acCode) {
this.acCode = acCode;
}


public Integer getAttId() {
return attId;
}


public void setAttId(Integer attId) {
this.attId = attId;
}


public String getAttIdStr() {
return attIdStr;
}
public void setAttIdStr(String attIdStr) {
this.attIdStr = attIdStr;
}
public Integer getAcId() {
return acId;
}


public String getAttIdDES() {
return attIdDES;
}
public void setAttIdDES(String attIdDES) {
this.attIdDES = attIdDES;
}
public void setAcId(Integer acId) {
this.acId = acId;
}


public String getAttCode() {
return attCode;
}


public void setAttCode(String attCode) {
this.attCode = attCode;
}


public String getPkValue() {
return pkValue;
}


public void setPkValue(String pkValue) {
this.pkValue = pkValue;
}


public String getAttPath() {
return attPath;
}


public void setAttPath(String attPath) {
this.attPath = attPath;
}


public String getEmpCode() {
return empCode;
}


public void setEmpCode(String empCode) {
this.empCode = empCode;
}


public String getEmpName() {
return empName;
}


public void setEmpName(String empName) {
this.empName = empName;
}


public String getCreateTime() {
return createTime;
}


public void setCreateTime(String createTime) {
this.createTime = createTime;
}


public int getIsOpen() {
return isOpen;
}


public void setIsOpen(int isOpen) {
this.isOpen = isOpen;
}


public int getIsEnable() {
return isEnable;
}


public void setIsEnable(int isEnable) {
this.isEnable = isEnable;
}


public String getSchCode() {
return schCode;
}


public void setSchCode(String schCode) {
this.schCode = schCode;
}


public String getSchName() {
return schName;
}


public void setSchName(String schName) {
this.schName = schName;
}


public String getSchIsEnable() {
return schIsEnable;
}


public void setSchIsEnable(String schIsEnable) {
this.schIsEnable = schIsEnable;
}


public Integer getCheckedAttConfigId() {
return checkedAttConfigId;
}


public void setCheckedAttConfigId(Integer checkedAttConfigId) {
this.checkedAttConfigId = checkedAttConfigId;
}


public String getFileExt() {
return fileExt;
}


public void setFileExt(String fileExt) {
this.fileExt = fileExt;
}


public Integer getFileSize() {
return fileSize;
}


public void setFileSize(Integer fileSize) {
this.fileSize = fileSize;
}


public String[] getTitle() {
return title;
}


public void setTitle(String[] title) {
this.title = title;
}


public String[] getNote() {
return note;
}


public void setNote(String[] note) {
this.note = note;
}
public Integer getSchAcId() {
return schAcId;
}
public void setSchAcId(Integer schAcId) {
this.schAcId = schAcId;
}
public String getSchAttCode() {
return schAttCode;
}
public void setSchAttCode(String schAttCode) {
this.schAttCode = schAttCode;
}
public String getSchPkValue() {
return schPkValue;
}
public void setSchPkValue(String schPkValue) {
this.schPkValue = schPkValue;
}
public String getSchTitle() {
return schTitle;
}
public void setSchTitle(String schTitle) {
this.schTitle = schTitle;
}
public String getSchEmpCode() {
return schEmpCode;
}
public void setSchEmpCode(String schEmpCode) {
this.schEmpCode = schEmpCode;
}
public String getSchEmpName() {
return schEmpName;
}
public void setSchEmpName(String schEmpName) {
this.schEmpName = schEmpName;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public InputStream getTargetFile() {
return targetFile;
}
public void setTargetFile(InputStream targetFile) {
this.targetFile = targetFile;
}
public String getContentDisposition() {
return contentDisposition;
}
public void setContentDisposition(String contentDisposition) {
this.contentDisposition = contentDisposition;
}
public void setIsDelete(int isDelete) {
this.isDelete = isDelete;
}
public void setIsOne(int isOne) {
this.isOne = isOne;
}
public void setIsBatch(int isBatch) {
this.isBatch = isBatch;
}
}

3 jsp 

<a href="downloadAttachment?attIdDES=76ced12aeb8fb1ff&amp;acCode=USER_PHOTO&amp;pkValue=111865">下载</a>

<a href="previewAttachment?attIdDES=76ced12aeb8fb1ff" target="_blank">预览</a>

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 ThinkPHP6 ,要实现将 OSS(阿里云对象存储) 的文件下载浏览器,需要使用 OSS SDK。下面是具体的实现步骤: 1. 安装 OSS SDK 使用 Composer 安装 OSS SDK: ``` composer require aliyuncs/oss-sdk-php ``` 2. 在控制器引入 OSS SDK 在控制器引入 OSS SDK: ```php use OSS\OssClient; use OSS\Core\OssException; ``` 3. 定义下载方法 在控制器定义下载方法: ```php public function downloadOssFile() { $accessKeyId = 'yourAccessKeyId'; // 填写阿里云 OSS 的 AccessKeyId $accessKeySecret = 'yourAccessKeySecret'; // 填写阿里云 OSS 的 AccessKeySecret $endpoint = 'yourEndpoint'; // 填写阿里云 OSS 的 endpoint $bucket = 'yourBucket'; // 填写阿里云 OSS 的 bucket 名称 $object = 'yourObject'; // 填写要下载的文件在 OSS 的 object 名称 try { $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint); // 判断要下载的文件是否存在 if (!$ossClient->doesObjectExist($bucket, $object)) { throw new OssException('要下载的文件不存在!'); } // 获取要下载的文件的元信息 $objectMeta = $ossClient->getObjectMeta($bucket, $object); // 设置要下载的文件的名称 $filename = '要下载的文件的名称'; // 设置要下载的文件的内容类型 $contentType = $objectMeta['content_type']; // 设置要下载的文件的长度 $contentLength = $objectMeta['content-length']; // 设置要下载的文件的内容 $content = $ossClient->getObject($bucket, $object); // 将文件以下载方式输出到浏览器 return Response::create($content, '200', [ 'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0', 'Content-Disposition' => 'attachment; filename=' . $filename, 'Content-Length' => $contentLength, 'Content-Type' => $contentType, 'Expires' => '0', 'Pragma' => 'public', ])->send(); } catch (OssException $e) { return $e->getMessage(); } } ``` 其,`$accessKeyId`、`$accessKeySecret`、`$endpoint`、`$bucket`、`$object` 都需要替换成自己的阿里云 OSS 的信息。 4. 定义路由 在路由定义路由规则: ```php Route::get('download_oss_file', '控制器名/downloadOssFile'); ``` 其,`download_oss_file` 为路由地址,`控制器名` 为具体的控制器名称。 5. 访问下载链接 在浏览器访问 `http://localhost/download_oss_file` 即可下载 OSS 的文件到浏览器

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值