上传方法(前后端) 公共方法

vue
 <el-col :span="24">
          <el-form-item label="证明文件" prop="fileList">
            <el-upload
              class="upload-demo inline-block"
              :multiple="multiple"
              action="/api/common/uploadfile"
              :on-success="uploadSuccess"
              :data="{fileSource: '特殊情况申报'}"
              :on-change="fileChange"
              :file-list="inputForm.fileList">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
        </el-col>



 uploadSuccess (response, file, fileList) {
        const responseData = response
        file.id = responseData.id
      },
      fileChange (file, fileList) {
        this.inputForm.fileList = fileList
      }

公共方法

package com.jeeplus.modules.files;

import com.jeeplus.plugin.Plugin;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "ds.plugin")
@PropertySource(value={"classpath:files-plugin.properties"}, encoding = "UTF-8")
public class FilesManagerPlugin  extends Plugin {

   @Override
   public void init() {
       System.out.println("文件管理加载完成");
   }
}

controller

package com.jeeplus.modules.files.web;

import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.files.entity.FilesInfo;
import com.jeeplus.modules.files.service.FileInfoService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.UUID;


@RestController
@RequestMapping(value = "/common")
public class FilesUploadController extends BaseController {

   @Value("${dirPath}")
   private String dirPath;
   @Autowired
   private FileInfoService service;

   @PostMapping(value = "/uploadfile")
   public AjaxJson upload(@RequestParam("file") MultipartFile file, HttpServletRequest request,@RequestParam("fileSource")String fileSource) {
       String sysDirPath = getFilesBaseDir(dirPath,fileSource);
       String oldname = file.getOriginalFilename(); // 用于数据库的filerealname
       String newname = UUID.randomUUID().toString().replaceAll("-","") + oldname.substring(oldname.lastIndexOf(".")); // 上传于数据的filename
//
       try {
           file.transferTo(new File(sysDirPath+File.separator+fileSource, newname));
       } catch (IllegalStateException e) {
           e.printStackTrace();
       } catch (IOException e) {
           e.printStackTrace();
       }
       FilesInfo s = new FilesInfo();
       s.setFileName(newname);
       s.setFileSource(fileSource);
       s.setDirPath(sysDirPath);
       s.setFilePath(fileSource);
       s.setFileResourceName(oldname);
       String recordId = service.saveRecord(s);
       return AjaxJson.success().put("id",recordId);
   }

   /**
    * 检查基文件夹,如果文件夹不存在则创建 如果存在同名文件 则增加Dir后缀后重试
    */
   private String getFilesBaseDir(String tempDirPath,String fileSource) {
       //如果没配置文件存放基目录路径
       if(StringUtils.isBlank(tempDirPath)){
           //取java配置的用户当前工作目录下smartbiUserFiles文件夹作为基目录
           tempDirPath = System.getProperty("user.dir");
           if(tempDirPath.endsWith(File.separator)){
               tempDirPath = tempDirPath + "smartbiUserFiles";
           }else{
               tempDirPath = tempDirPath + File.separator + "smartbiUserFiles";
           }
       }
       if(!tempDirPath.endsWith(File.separator)){
           tempDirPath = tempDirPath + File.separator;
       }
       //检查文件夹可用性
       File dirPathFile = new File(tempDirPath + fileSource);
       if(!dirPathFile.exists()){
           dirPathFile.mkdirs();
       }

       //如果当前路径不是文件夹或者没有可写入权限 在路径最后加Dir重试
       if(!(dirPathFile.isDirectory() && dirPathFile.canWrite())){
           tempDirPath += "Dir";
           return getFilesBaseDir(tempDirPath,fileSource);
       }

       return tempDirPath;
   }


   @GetMapping("downloadUploadFile/{id}")
   @ResponseBody
   public void downloadUploadFile(@PathVariable(name = "id") String id,HttpServletResponse response, HttpServletRequest request){
       FilesInfo filesInfo = service.get(id);
       if(null == filesInfo){
           setErrorAlert(response,"找不到文件信息,请刷新后重试");
       }else{
           String dirPath = filesInfo.getDirPath();
           String filePath = filesInfo.getFilePath();
           String fileName = filesInfo.getFileName();
           String fileUserName = filesInfo.getName();
           String fileRealResourcePath = dirPath+filePath+File.separator+fileName;
           File file = new File(fileRealResourcePath);
           if(file.exists()){
               if(file.canRead()){
                   writeFileToResponse(response,request,fileUserName,file);
               }else{
                   setErrorAlert(response,"文件无法读取,文件系统权限不足");
               }
           }else{
               setErrorAlert(response,"文件不存在,可能是已在文件系统中移动到其他位置或删除");
           }
       }

   }

   /**
    * 在页面弹出错误信息
    * @param response
    * @param errorMsg 显示的错误信息
    */
   private void setErrorAlert(HttpServletResponse response,String errorMsg) {
       response.setContentType("text/html; charset=UTF-8"); //转码
       try (PrintWriter out = response.getWriter()){
           out.flush();
           out.println("<script>");
           out.println("alert('"+errorMsg+"');");
           out.println("</script>");
       } catch (IOException ioException) {
           logger.error("无法返回错误信息",ioException);
       }
   }

   /**
    * 将文件写入响应流
    * @param response
    * @param request
    * @param fileName
    * @param templateFile
    * @return
    */
   private void writeFileToResponse(HttpServletResponse response, HttpServletRequest request, String fileName, File templateFile) {
       try (OutputStream out=response.getOutputStream(); FileInputStream fis = new FileInputStream(templateFile); BufferedInputStream bis = new BufferedInputStream(fis)){
           setResponseHeader(response, request, fileName);
           byte[] buffer = new byte[1024];
           int i =bis.read(buffer);
           while(i != -1){
               out.write(buffer,0,i);
               i =bis.read(buffer);
           }
           out.flush();
       } catch (IOException e) {
           logger.error("向Response输出内容时出错",e);
       }
   }

   /**
    * 设置响应头
    * @param response
    * @param request
    * @param fileName
    * @throws UnsupportedEncodingException
    */
   private void setResponseHeader(HttpServletResponse response, HttpServletRequest request, String fileName) throws UnsupportedEncodingException {
       response.setHeader("content-type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
       response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf8");
       String userAgent = request.getHeader("User-Agent");
       if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
           response.setHeader("Content-disposition",
                   String.format("attachment; filename=\"%s\"", java.net.URLEncoder.encode(fileName, "UTF-8")));
       } else {
           response.setHeader("Content-disposition",
                   String.format("attachment; filename=\"%s\"", new String((fileName).getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1)));
       }
   }
}

service

/**
* Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
*/
package com.jeeplus.modules.files.service;

import java.util.List;

import com.jeeplus.modules.files.entity.FilesInfo;
import com.jeeplus.modules.files.mapper.FileInfoMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.service.CrudService;

/**
* 文件管理Service
* @author 郑博智
* @version 2020-10-29
*/
@Service
@Transactional(readOnly = true)
public class FileInfoService extends CrudService<FileInfoMapper, FilesInfo> {

   public FilesInfo get(String id) {
   	return super.get(id);
   }
   
   public List<FilesInfo> findList(FilesInfo filesInfo) {
   	return super.findList(filesInfo);
   }
   
   public Page<FilesInfo> findPage(Page<FilesInfo> page, FilesInfo filesInfo) {
   	return super.findPage(page, filesInfo);
   }
   
   @Transactional(readOnly = false)
   public String saveRecord(FilesInfo filesInfo) {
   	if (filesInfo.getIsNewRecord()){
   		filesInfo.preInsert();
   		mapper.insertRecord(filesInfo);
   		return filesInfo.getId();
   	}else{
   		filesInfo.preUpdate();
   		mapper.updateRecord(filesInfo);
   		return filesInfo.getId();
   	}
   }
   
   @Transactional(readOnly = false)
   public void delete(FilesInfo filesInfo) {
   	super.delete(filesInfo);
   }
}

mapper

/**
* Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
*/
package com.jeeplus.modules.files.mapper;

import com.jeeplus.modules.files.entity.FilesInfo;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import com.jeeplus.core.persistence.BaseMapper;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

/**
* 文件管理MAPPER接口
* @author 郑博智
* @version 2020-10-29
*/
@Mapper
@Repository
public interface FileInfoMapper extends BaseMapper<FilesInfo> {

   /**
    * 插入数据
    * @param entity
    * @return
    */
   @Deprecated
   public default int insert(FilesInfo entity){
       return this.insertRecord(entity);
   };

   /**
    * 更新数据
    * @param entity
    * @return
    */
   @Deprecated
   public default int update(FilesInfo entity){
       return this.updateRecord(entity);
   };


   /**
    * 插入数据
    * @param entity
    * @return
    */

   public int insertRecord(FilesInfo entity);

   /**
    * 更新数据
    * @param entity
    * @return
    */
   public int updateRecord(FilesInfo entity);

   void updateAllOldFilesMainIdToNull(@Param("id") String id, @Param("tableName") String tableName);

   void updateNewFilesMainId(FilesInfo fileList);
}
<?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="com.jeeplus.modules.files.mapper.FileInfoMapper">

   <sql id="tFileResourceInfoColumns">
   	a.id AS "id",
   	a.file_name AS "fileName",
   	a.file_source AS "fileSource",
   	a.dir_path AS "dirPath",
   	a.file_path AS "filePath",
   	a.file_resource_name AS "fileResourceName",
   	a.main_record_id AS "mainRecordId",
   	a.main_record_table AS "mainRecordTable"
   </sql>

   <sql id="tFileResourceInfoJoins">

   </sql>


   <select id="get" resultType="FilesInfo" >
   	SELECT
   		<include refid="tFileResourceInfoColumns"/>
   	FROM t_file_resource_info a
   	<include refid="tFileResourceInfoJoins"/>
   	WHERE a.id = #{id}
   </select>

   <select id="findList" resultType="FilesInfo" >
   	SELECT
   		<include refid="tFileResourceInfoColumns"/>
   	FROM t_file_resource_info a
   	<include refid="tFileResourceInfoJoins"/>
   	<where>
   		
   		${dataScope}
   	</where>
   	<choose>
   		<when test="page !=null and page.orderBy != null and page.orderBy != ''">
   			ORDER BY ${page.orderBy}
   		</when>
   		<otherwise>
   		</otherwise>
   	</choose>
   </select>

   <select id="findAllList" resultType="FilesInfo" >
   	SELECT
   		<include refid="tFileResourceInfoColumns"/>
   	FROM t_file_resource_info a
   	<include refid="tFileResourceInfoJoins"/>
   	<where>
   		
   		${dataScope}
   	</where>
   	<choose>
   		<when test="page !=null and page.orderBy != null and page.orderBy != ''">
   			ORDER BY ${page.orderBy}
   		</when>
   		<otherwise>
   		</otherwise>
   	</choose>
   </select>

   <insert id="insertRecord">
   	INSERT INTO t_file_resource_info(
   		id,
   		file_name,
   		file_source,
   		dir_path,
   		file_path,
   		file_resource_name,
   		main_record_id,
   		main_record_table
   	) VALUES (
   		#{id},
   		#{fileName},
   		#{fileSource},
   		#{dirPath},
   		#{filePath},
   		#{fileResourceName},
   		#{mainRecordId},
   		#{mainRecordTable}
   	)
   </insert>

   <update id="updateRecord">
   	UPDATE t_file_resource_info
   	      <set>
   			  <if test="fileName != null">
   				  file_name = #{fileName},
   			  </if>
   			  <if test="fileSource != null">
   				  file_source = #{fileSource},
   			  </if>
   			  <if test="dirPath != null">
   				  dir_path = #{dirPath},
   			  </if>
   			  <if test="filePath != null">
   				  file_path = #{filePath},
   			  </if>
   			  <if test="fileResourceName != null">
   				  file_resource_name = #{fileResourceName},
   			  </if>
   			  <if test="mainRecordId != null">
   				  main_record_id = #{mainRecordId},
   			  </if>
   			  <if test="mainRecordTable != null">
   				  main_record_table = #{mainRecordTable}
   			  </if>
   		  </set>
   	WHERE id = #{id}
   </update>


   <!--物理删除-->
   <update id="delete">
   	DELETE FROM t_file_resource_info
   	WHERE id = #{id}
   </update>


   <!-- 根据实体名称和字段名称和字段值获取唯一记录 -->
   <select id="findUniqueByProperty" resultType="TFileResourceInfo" statementType="STATEMENT">
   	select * FROM t_file_resource_info  where ${propertyName} = '${value}'
   </select>
   <update id="updateAllOldFilesMainIdToNull">
   	update t_file_resource_info set main_record_table = null,main_record_id = null where main_record_id = #{id} and main_record_table = #{tableName}
   </update>
   <update id="updateNewFilesMainId">
   	update t_file_resource_info set main_record_table = #{mainRecordTable},main_record_id = #{mainRecordId} where id = #{id}
   </update>

</mapper>

entity

    private String id; //资源号
    private String name; //前台显示的文件名
    private String fileName; //文件显示名
    private String fileSource; //文件来源(模块功能名,配置到下拉框中)
    private String dirPath; //文件目录(相对于文件系统根目录)
    private String filePath; //文件存放路径(服务器上的相对与dir_path的路径,不含目标文件名)
    private String fileResourceName; //文件名称(服务器上的文件名)
    private String mainRecordId; //主记录id
    private String mainRecordTable; //主记录表名

entity

public class TSpecialMatter extends DataEntity<TSpecialMatter> {
	
	private static final long serialVersionUID = 1L;
	private String year;		// 年度
	private String proposerId;		// 申请人id 关联t_worker_baseinfo.id
	private String matterType;		// 事项类型
	private Date beginTime;		// 开始时间
	private Date endTime;		// 结束时间
	private String matterDetail;		// 事项说明
	private String aduitStatus;		// 审核状态
	private String aduitPersonId;		// 审核人id
	private String workerNo;//教工编码
	private String workerName;//教工姓名
	private String name;//名称
	private String SeveralFiles; // 证明文件
    private Office office;
    private User user;
	private FilesInfo[] fileList;
deleteAllOldFilesAndInsertNewFiles(entity.getId(),"t_special_matter",entity.getFileList());

	}

	private void deleteAllOldFilesAndInsertNewFiles(String id, String tableName, FilesInfo[] fileList) {
		fileMapper.updateAllOldFilesMainIdToNull(id,tableName);
//        List<FilesInfo> newFileList = new ArrayList<>();
		if(null!=fileList){
			for(int i=0;i<fileList.length;i++){
				FilesInfo fileInfo = fileList[i];
				fileInfo.setMainRecordTable(tableName);
				fileInfo.setMainRecordId(id);
				fileMapper.updateNewFilesMainId(fileInfo);
			}
		}
	}
  public int updateRecord(FilesInfo entity);

    void updateAllOldFilesMainIdToNull(@Param("id") String id, @Param("tableName") String tableName);

    void updateNewFilesMainId(FilesInfo fileList);
	<!-- 根据实体名称和字段名称和字段值获取唯一记录 -->
 <select id="findUniqueByProperty" resultType="TFileResourceInfo" statementType="STATEMENT">
 	select * FROM t_file_resource_info  where ${propertyName} = '${value}'
 </select>
 <update id="updateAllOldFilesMainIdToNull">
 	update t_file_resource_info set main_record_table = null,main_record_id = null where main_record_id = #{id} and main_record_table = #{tableName}
 </update>
 <update id="updateNewFilesMainId">
 	update t_file_resource_info set main_record_table = #{mainRecordTable},main_record_id = #{mainRecordId} where id = #{id}
 </update>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值