ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

上传下载---图片|文件

2021-08-21 22:05:25  阅读:116  来源: 互联网

标签:String attachId 上传下载 fileName --- attach import public 图片


说明。此样例是把图片或者文件上传到数据库的blob或者clob字段里头进行存储

controller层

package com.site.biz.controller.common;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.gta.edu.sdk.common.dto.ResultData;
import com.site.api.attach.FileResult;
import com.site.api.attach.service.IAttachService;
import com.site.api.attach.vo.GovsAttachVo;
import com.site.biz.controller.BaseController;

import io.swagger.annotations.Api;
@Api("文件上传")
@Controller
@RequestMapping("/fileCommon")
public class FileCommonController extends BaseController {
    private static final Logger LOG = LogManager.getLogger(FileCommonController.class);
    @Autowired
    private IAttachService attachService;

    @RequestMapping(value="/upload", method = RequestMethod.POST)
    @ResponseBody
    public ResultData upload(@RequestParam("file") MultipartFile file) {
        ResultData rd = new ResultData();
        rd.setSuccess(false);
        String fileName = file.getOriginalFilename();
        try {
            FileResult fr = attachService.save(fileName, file.getBytes());
            if (fr.isResultFlag()) {
                rd.setSuccess(true);
                Map<String, String> map = new HashMap<String, String>();
                map.put("attachId", fr.getAttachId());
                rd.setData(map);
            } else {
                rd.setErrorMsg(fr.getFailedMsg());
            }
        } catch (IOException e) {
            LOG.error("", e);
            rd.setErrorMsg("文件上传异常");
        }
        return rd;
    }

    @RequestMapping(value = "/getImg", method = RequestMethod.GET)
    public void getImg(HttpServletRequest request, HttpServletResponse response){
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/png");
        String attachId = request.getParameter("attachId");
        GovsAttachVo attach = attachService.queryAttach(attachId);
        if(LOG.isInfoEnabled()) {
            LOG.info("getimg.attachId={}", attachId);
        }
        if(attach != null && attach.getFileContent()!=null) {
            //String base64=Base64.encodeBase64String(attach.getFileContent());
            OutputStream os = null;
            try {
                os = response.getOutputStream();
                os.write(attach.getFileContent());
                os.flush();
            } catch (IOException e) {
                LOG.error("", e);
            }finally {
                if(os != null) {
                    try {
                        os.close();
                    } catch (IOException e) {
                        LOG.error("", e);
                    }
                }
            }
            
            
        }

    }
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public void download(HttpServletRequest request, HttpServletResponse response) {
        String attachId = request.getParameter("attachId");
        GovsAttachVo attach = attachService.queryAttach(attachId);
        if(LOG.isInfoEnabled()) {
            LOG.info("download.attachId={}", attachId);
        }
        if(attach != null && attach.getFileContent()!=null) {
            OutputStream os=null;
            response.setContentType("bin");
            response.reset();
            response.setContentType("application/ms-excel;charset=utf-8");
            response.setCharacterEncoding("UTF-8");
            response.addHeader("Cache-Control", "no-cache");
            String fileName = attach.getFileName();
            try {
                response.setHeader("Content-disposition", "attachment;filename="+URLEncoder.encode(fileName,"UTF-8"));
                os=response.getOutputStream();
                os.write(attach.getFileContent());
                os.flush();
            } catch (UnsupportedEncodingException e) {
                LOG.error("", e);
            } catch (IOException e) {
                LOG.error("", e);
            }finally {
                if(os != null) {
                    try {
                        os.close();
                    } catch (IOException e) {
                        LOG.error("", e);
                    }
                }
            }
            
        }
    }
}
View Code

 

server接口层

package com.site.api.attach.service;

import java.util.List;

import com.site.api.attach.FileResult;
import com.site.api.attach.vo.GovsAttachVo;

public interface IAttachService {
    /**
     * 保存附件,返回附件保存结果信息
     * @param fileName 附件文件名
     * @param fileContent 附件文件内容
     * @return
     */
    public FileResult save(String fileName,byte[]fileContent);
    /**
     * 保存附件,返回附件保存结果信息
     * @param fileName 附件文件名
     * @param fileContent 附件文件内容
     * @param realTable 关联的表名或模块名
     * @param realTableId 关联的表名主键id
     * @return
     */
    public FileResult save(String fileName,byte[]fileContent,String realTable,String realTableId);
    /**
     * 保存附件,返回附件保存结果信息
     * @param fileName 附件文件名
     * @param fileContent 附件文件内容
     * @param realTable 关联的表名或模块名
     * @param realTableId 关联的表名主键id
     * @param seq 附件序号
     * @return
     */
    public FileResult save(String fileName,byte[]fileContent,String realTable,String realTableId,int seq);
    /**
     * 根据附件id删除附件
     * @param attachId
     * @return
     */
    public boolean delete(String attachId);
    /**
     * 根据关联的表名或模块名和关联的表名主键id删除附件
     * @param realTable
     * @param realTableId
     * @return
     */
    public boolean delete(String realTable,String realTableId);
    /**
     *  根据关联的表名或模块名和关联的表名主键id查询附件
     * @param realTable
     * @param realTableId
     * @return
     */
    public List<GovsAttachVo> queryAttach(String realTable,String realTableId);
    /**
     * 根据附件id查询附件
     * @param attachId
     * @return
     */
    public GovsAttachVo queryAttach(String attachId);
    
}
View Code

 

server实现层

package com.site.biz.service.attach;

import java.util.List;
import java.util.Locale;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.common.core.DaoSeqUtils;
import com.common.core.FileTypeUtil;
import com.site.api.attach.FileResult;
import com.site.api.attach.bo.GovsAttachBo;
import com.site.api.attach.bo.GovsAttachRealBo;
import com.site.api.attach.dao.IGovsAttachDao;
import com.site.api.attach.dao.IGovsAttachRealDao;
import com.site.api.attach.service.IAttachService;
import com.site.api.attach.vo.GovsAttachVo;
import org.springframework.transaction.annotation.Transactional;

@Service
public class AttachServiceImpl implements IAttachService{
    private static final Logger LOG = LogManager.getLogger(AttachServiceImpl.class);
    @Autowired
    private IGovsAttachDao attachDao;
    @Autowired
    private IGovsAttachRealDao attachRealDao;
    @Override
    public FileResult save(String fileName, byte[] fileContent) {
        return save(fileName,fileContent,null,"0");
    }
    @Override
    public FileResult save(String fileName, byte[] fileContent, String realTable, String realTableId) {
        return save(fileName,fileContent,realTable,realTableId,1);
    }
    @Override
    @Transactional
    public boolean delete(String attachId) {
        attachDao.delete(attachId);
        attachRealDao.delete(attachId);
        return false;
    }
    @Override
    @Transactional
    public boolean delete(String realTable, String realTableId) {
        GovsAttachRealBo attach = new GovsAttachRealBo ();
        attach.setRealTable(getRealTable(realTable));
        attach.setRealTableId(realTableId);
        attachDao.delete(attach);
        attachRealDao.delete(attach);
        return false;
    }
    @Override
    public List<GovsAttachVo> queryAttach(String realTable, String realTableId) {
        GovsAttachRealBo attach = new GovsAttachRealBo ();
        attach.setRealTable(getRealTable(realTable));
        attach.setRealTableId(realTableId);
        return attachRealDao.queryAttach(attach);
    }
    @Override
    public GovsAttachVo queryAttach(String attachId) {
        return attachRealDao.queryAttach(attachId);
    }

    @Override
    @Transactional
    public FileResult save(String fileName, byte[] fileContent, String realTable, String realTableId, int seq) {
        FileResult fr = new FileResult();
        fr.setResultFlag(false);
        if(StringUtils.isEmpty(fileName)) {
            fr.setFailedMsg("文件名不能为空");
            return fr;
        }
        if(fileContent==null || fileContent.length==0) {
            fr.setFailedMsg("文件内容不能为空");
            return fr;
        }
        String type = FileTypeUtil.getFileType(fileContent);
        if(StringUtils.isEmpty(type)) {
            LOG.warn("fileName={},上传的文件类型非法", fileName);
            fr.setFailedMsg("["+fileName+"]为非法文件类型");
            return fr;
        }
        int index = fileName.lastIndexOf(".");
        if(index<=0||(index+1)==fileName.length()) {
            fr.setFailedMsg("["+fileName+"]非法的文件名称");
            return fr;
        }
        String fileNameType = fileName.substring(index+1);
        if(LOG.isInfoEnabled()) {
            LOG.info("fileName={},获取的实际文件后缀:{}",fileName,type);
        }
        if(!type.equals(fileNameType)) {
            fr.setFailedMsg("["+fileName+"]上传的文件类型被篡改");
            return fr;
        }
        fr.setResultFlag(true);
        GovsAttachBo att = new GovsAttachBo();
        att.setAttachId(DaoSeqUtils.getUUID());
        att.setFileContent(fileContent);
        att.setFileName(fileName);
        att.setFileType(type);
        attachDao.save(att);
        GovsAttachRealBo real = new GovsAttachRealBo();
        real.setAttachId(att.getAttachId());
        real.setAttaRealId(DaoSeqUtils.getUUID());
        real.setAttSeq(seq);
        real.setRealTableId(realTableId);
        real.setRealTable(getRealTable(realTable));
        attachRealDao.save(real);
        fr.setAttachId(att.getAttachId());
        return fr;
    }
    
    private String getRealTable(String realTable) {
        if(StringUtils.isEmpty(realTable)) {
            return null;
        }
        return realTable.toUpperCase(Locale.ENGLISH);
    }


}
View Code

 

dao实现层这边就不举例了。简单的将数据插入进去即可。注意文件存放字段 要用大字段。blob类型即可

标签:String,attachId,上传下载,fileName,---,attach,import,public,图片
来源: https://www.cnblogs.com/linhongwenBlog/p/14549802.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有