码迷,mamicode.com
首页 > 编程语言 > 详细

Spring MVC 文件上传与下载2及分页功能

时间:2019-02-19 10:31:37      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:parameter   esb   log   png   rownumber   logger   后缀   entity   方法   

Service 方法
public List<Map<String,Object>> handleMultipartRequest(String fileGuid, MultipartRequest request, HttpServletRequest httpServletRequest) throws Exception {
List<Map<String, Object>> uploadFileList=new ArrayList<Map<String,Object>>();
Set<Entry<String, List<MultipartFile>>> params = request.getMultiFileMap().entrySet();
if(StringUtils.isEmpty(fileGuid)) {
fileGuid=guidGeneratorUtil.getUUID();
}
for(Entry<String, List<MultipartFile>> param : params) {
for(MultipartFile file: param.getValue()) {
if(StringUtils.isEmpty(file.getOriginalFilename())) {
logger.info("key=uploadfile File OriginalFilename is Empty.");
continue;
}
Map<String, Object> fileMap= handleMultipartFile(file);
fileMap.put("FileGuid", fileGuid);
fileUploadDataDao.insertFileUploadData(fileMap);
uploadFileList.add(fileMap);
}
}
return uploadFileList;
}

public Map<String, Object> handleMultipartFile(MultipartFile file) throws Exception{
    Map<String, Object> rMap=new HashMap<>();
    String msg = null;
    String extensionName=getExtensionName(file.getOriginalFilename());
    if(!checkFileExtensionName(extensionName)) {
         msg = String.format("key=uploadfile FileExtensionName:%s 文件后缀错误", extensionName);
        //logger.error(msg);
        throw new Exception(msg);
    }
    String fileId=guidGeneratorUtil.getFileId();
    rMap.put("FileId", fileId);
    StringBuilder fileSB=new StringBuilder();
    DateFormat dFormat=new SimpleDateFormat("yyyyMMdd");
    Date date =new Date();
    fileSB.append(uploadPath+dFormat.format(date));
    File destParnetFile=new File(fileSB.toString());
    if(!destParnetFile.exists()) {
        destParnetFile.mkdirs();  //如果目录不存在,则创建
    }
    File dest=new File(fileSB.toString(), fileId);
    try {
        file.transferTo(dest);  //保存文件到本地磁盘
    } catch (IllegalStateException | IOException e) {
        msg=String.format("key=uploadfile %s", e.getMessage());
        //logger.error(msg);
        throw new Exception(msg); 
    }
    rMap.put("FilePath", fileSB.toString());
    rMap.put("FileName", file.getOriginalFilename());
    rMap.put("FileType", extensionName);
    rMap.put("FileSize", file.getSize());
    return rMap;

}

/**
 * @param fileName
 * @return
 */
public String getExtensionName(String fileName) {
    String extensionName="";
    if(StringUtils.isEmpty(fileName)) {
        return extensionName;
    }
    int startIndex=fileName.indexOf(".");
    extensionName=fileName.substring(startIndex+1);
    return extensionName;
}

/**
 * @param extensionName 文件扩展名称
 * @return  返回true可以上传,返回false不可以上传
 */
private Boolean checkFileExtensionName(String extensionName) {
    boolean flag=false;  
    if(StringUtils.isEmpty(extensionName)) {
        return flag;
    }
    String[] appExtArr=StringUtils.tokenizeToStringArray(appExtStr, ",");
    for (String m : appExtArr) {
        if(extensionName.equals(m)) {
            flag=true;
            break;
        }
    }

    return flag;
}

public List<Map<String, Object>>  getFileUploadDataList(Map<String, Object> map){
    List<Map<String, Object>> rList = new ArrayList<>();
    rList=fileUploadDataDao.getFileUploadDataList(map);
    return rList;
}

public int  getFileUploadDataListCnt(Map<String, Object> map) {
    int result=0;
    result = fileUploadDataDao.getFileUploadDataListCnt(map);
    return result;
}

public File getUploadFile(Map<String, Object> map) throws Exception {
    Map<String, Object> fileMap= fileUploadDataDao.getFileUploadData(map).get(0);
    if(fileMap == null || fileMap.size() <=0) {
        throw new Exception("file data does not exist.");
    }
    StringBuilder sb = new StringBuilder();
    sb.append(fileMap.get("FilePath"));
    sb.append("/");
    sb.append(fileMap.get("FileId"));
    return new File(sb.toString());

}

SQL脚本
<select id="getFileUploadDataList" parameterType="java.util.Map"
    resultType="java.util.Map">
    <include refid="paging.pagingPreSQL" />
    select ROW_NUMBER() over(order by Number desc )
    rownum,[Number]
    ,[FileGuid]
    ,[FileId]
    ,[FilePath]
    ,[FileName]
    ,[FileType]
    ,[FileSize]
    ,[CreateTime]
    from AA_FileUploadData
    where 1=1
    <if test="FileGuid !=null and FileGuid !=‘‘ ">
        AND FileGuid= #{FileGuid}
    </if>
    <if test="FileId !=null and FileId !=‘‘ ">
        AND FileId= #{FileId}
    </if>
    <include refid="paging.pagingPostSQL" />
</select>
<insert id="insertFileUploadData" parameterType="java.util.Map">
    <selectKey resultType="int" keyProperty="Number" order="AFTER">
        select
        @@IDENTITY as id
    </selectKey>
    INSERT INTO [dbo].[AA_FileUploadData]
    ([FileGuid]
    ,[FileId]
    ,[FilePath]
    ,[FileName]
    ,[FileType]
    ,[FileSize]
    ,[CreateTime])
    VALUES
    (
    #{FileGuid},
    #{FileId},
    #{FilePath},
    #{FileName},
    #{FileType},
    #{FileSize},
    GetDate()
    )
</insert>
分页抽象
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">;
<mapper namespace="paging">

<!-- ???? ?? ?? QUERY ???..??? ?? ????? ?? ????.. -->
<sql id="pagingPreSQL">
    SELECT * FROM (
    SELECT ROWNUM AS "ROWNUMBER" , AA.* FROM (
</sql>

<sql id="pagingPostSQL">
    ) AA ) AAA
     <![CDATA[
        WHERE AAA.ROWNUMBER  >= #{firstRowIndex} AND  AAA.ROWNUMBER  <= #{lastRowIndex}
     ]]>
</sql>

<sql id="pagingPreSqlOverCount">
    SELECT FLOOR((AA.totalCount-1)/#{rowPerPage})+1 totalPage , AA.* FROM (
    SELECT COUNT(*) OVER() totalCount, ROWNUM ROWNUMBER,MAINSQL.* FROM
    (
</sql>

<sql id="pagingPostSqlOverCount">

    ) MAINSQL 
     <![CDATA[ ) AA WHERE ROWNUMBER>=((#{pageNo}-1)*#{rowPerPage})+1 AND ROWNUMBER <= (((#{pageNo}-1)*#{rowPerPage})+1) + #{rowPerPage}-1 ]]>
</sql>

/mapper>
固定字符串注解
@Value("${file.extension.approve.list}")
private String appExtStr;
configuration.properties 属性文件
file.extension.approve.list=dat,doc,docx,xlsx,xls,ppt,pptx,txt,gif,jpg,png,pdf,bmp,zip
file.upload.path.localhost=F:/sprout/upload/
applicationContent.xml文件引入属性文件配置

Spring MVC 文件上传与下载2及分页功能

标签:parameter   esb   log   png   rownumber   logger   后缀   entity   方法   

原文地址:http://blog.51cto.com/6000734/2351657

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!