文件上传接口
This commit is contained in:
parent
5906f6cc50
commit
b57fd54e9e
|
|
@ -0,0 +1,92 @@
|
|||
package com.bonus.sgzb.system.controller;
|
||||
|
||||
import com.bonus.sgzb.common.core.utils.StringHelper;
|
||||
import com.bonus.sgzb.common.core.web.domain.AjaxResult;
|
||||
import com.bonus.sgzb.system.domain.FileInfo;
|
||||
import com.bonus.sgzb.system.service.SysFileService;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import org.apache.poi.util.IOUtils;
|
||||
import org.springframework.core.io.ResourceLoader;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.servlet.ServletOutputStream;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.InputStream;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/sys/file")
|
||||
public class SysFileController {
|
||||
|
||||
@Resource
|
||||
private SysFileService service;
|
||||
|
||||
@Resource
|
||||
private ResourceLoader resourceLoader;
|
||||
|
||||
|
||||
@PostMapping("/upload")
|
||||
@ApiOperation(value = "文件上传")
|
||||
public AjaxResult upload(HttpServletRequest request) {
|
||||
String limitWords = request.getParameter("limitWords");
|
||||
FileInfo file = new FileInfo();
|
||||
try {
|
||||
file = service.uploadFile(request);
|
||||
if (limitWords != null && file.getWords() > Integer.parseInt(limitWords)){
|
||||
return AjaxResult.error("上传文件字数超出限制字数!");
|
||||
}
|
||||
}catch (Exception e){
|
||||
e.printStackTrace();
|
||||
}
|
||||
if (file != null && file.getId() != 0){
|
||||
return AjaxResult.success(file);
|
||||
}else {
|
||||
return AjaxResult.error("文件上传失败!");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ApiOperation(value = "模板", httpMethod = "GET")
|
||||
@GetMapping("download")
|
||||
public void download(HttpServletRequest request, HttpServletResponse response, String filename) {
|
||||
InputStream inputStream = null;
|
||||
ServletOutputStream servletOutputStream = null;
|
||||
try {
|
||||
String path = "download/" + filename;
|
||||
org.springframework.core.io.Resource resource = resourceLoader.getResource("classpath:" + path);
|
||||
response.setContentType("application/vnd.ms-excel");
|
||||
response.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
|
||||
response.addHeader("charset", "utf-8");
|
||||
response.addHeader("Pragma", "no-cache");
|
||||
String encodeName = URLEncoder.encode(filename, StandardCharsets.UTF_8.toString());
|
||||
response.setHeader("Content-Disposition", "attachment; filename=\"" + encodeName + "\"; filename*=utf-8''" + encodeName);
|
||||
|
||||
inputStream = resource.getInputStream();
|
||||
servletOutputStream = response.getOutputStream();
|
||||
IOUtils.copy(inputStream, servletOutputStream);
|
||||
response.flushBuffer();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
try {
|
||||
if (servletOutputStream != null) {
|
||||
servletOutputStream.close();
|
||||
}
|
||||
if (inputStream != null) {
|
||||
inputStream.close();
|
||||
}
|
||||
// 召唤jvm的垃圾回收器
|
||||
System.gc();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,40 @@
|
|||
package com.bonus.sgzb.system.domain;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
@Data
|
||||
public class FileInfo {
|
||||
|
||||
/** $column.columnComment */
|
||||
private Long id;
|
||||
|
||||
/** 模块id */
|
||||
private Long modelId;
|
||||
/** 文件名称 */
|
||||
@ApiModelProperty(value = "文件名称")
|
||||
private String fileName;
|
||||
|
||||
/** 文件路径 */
|
||||
@ApiModelProperty(value = "文件路径")
|
||||
private String fileUrl;
|
||||
|
||||
/** 数据字典 */
|
||||
@ApiModelProperty(value = "数据字典")
|
||||
private Long dicId;
|
||||
|
||||
/** 创建者 */
|
||||
private String createBy;
|
||||
|
||||
/** 创建时间 */
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
private Date createTime;
|
||||
private String size;
|
||||
private String type;
|
||||
private int words;
|
||||
private String creator;
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
package com.bonus.sgzb.system.mapper;
|
||||
|
||||
import com.bonus.sgzb.system.domain.FileInfo;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Mapper 接口
|
||||
* </p>
|
||||
*
|
||||
* @author laker
|
||||
* @since 2021-08-05
|
||||
*/
|
||||
public interface FileInfoMapper {
|
||||
|
||||
int insertFileInfo(FileInfo o);
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
package com.bonus.sgzb.system.service;
|
||||
|
||||
|
||||
import com.bonus.sgzb.system.domain.FileInfo;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
/**
|
||||
* 文件上传接口
|
||||
*
|
||||
* @author zys
|
||||
*/
|
||||
public interface SysFileService
|
||||
{
|
||||
/**
|
||||
* 文件上传接口
|
||||
*
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
FileInfo uploadFile(HttpServletRequest request) throws Exception;
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,179 @@
|
|||
package com.bonus.sgzb.system.service.impl;
|
||||
|
||||
import cn.hutool.core.util.IdUtil;
|
||||
import com.bonus.sgzb.common.core.utils.DateTimeHelper;
|
||||
import com.bonus.sgzb.common.security.utils.SecurityUtils;
|
||||
import com.bonus.sgzb.system.api.model.LoginUser;
|
||||
import com.bonus.sgzb.system.domain.FileInfo;
|
||||
import com.bonus.sgzb.system.mapper.FileInfoMapper;
|
||||
import com.bonus.sgzb.system.service.SysFileService;
|
||||
import org.apache.poi.hwpf.extractor.WordExtractor;
|
||||
import org.apache.poi.openxml4j.util.ZipSecureFile;
|
||||
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
|
||||
import org.apache.poi.xwpf.usermodel.XWPFDocument;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.security.Security;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* 本地文件存储
|
||||
*
|
||||
* @author zys
|
||||
*/
|
||||
@Primary
|
||||
@Service("SysFileService")
|
||||
public class SysFileServiceImpl implements SysFileService {
|
||||
|
||||
@Resource
|
||||
private FileInfoMapper dao;
|
||||
|
||||
/**
|
||||
* 本地文件上传接口
|
||||
*
|
||||
* @return 访问地址
|
||||
* @throws Exception
|
||||
*/
|
||||
@Override
|
||||
public FileInfo uploadFile(HttpServletRequest request) throws Exception {
|
||||
FileInfo file = new FileInfo();
|
||||
StandardMultipartHttpServletRequest req = (StandardMultipartHttpServletRequest) request;
|
||||
String photoType = req.getParameter("fileType");
|
||||
String userId = req.getParameter("userId");
|
||||
HashMap<String, Object> map = getFile(req);
|
||||
List<MultipartFile> items = (List<MultipartFile>) map.get("filePath");
|
||||
MultipartFile item = items.get(0);
|
||||
try {
|
||||
String url = saveFile(request, item, photoType);
|
||||
if(url != null){
|
||||
int words = getFileText(item);
|
||||
String fileName = item.getOriginalFilename();
|
||||
String type = fileName.substring(fileName.lastIndexOf(".") + 1);
|
||||
long size = item.getSize()/1024/1024;
|
||||
file.setFileName(fileName);
|
||||
file.setFileUrl(url);
|
||||
file.setCreator(userId);
|
||||
file.setType(type);
|
||||
file.setSize(size + "M");
|
||||
file.setWords(words);
|
||||
file.setCreateBy(SecurityUtils.getUserId().toString());
|
||||
file.setCreateTime(new Date());
|
||||
dao.insertFileInfo(file);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return file;
|
||||
}
|
||||
|
||||
public HashMap<String, Object> getFile(StandardMultipartHttpServletRequest request) {
|
||||
MultipartFile multipartFile;
|
||||
HashMap<String, Object> map = new HashMap<String, Object>();
|
||||
try {
|
||||
List<MultipartFile> tmps = new ArrayList<MultipartFile>();
|
||||
Iterator<String> itr = request.getFileNames();
|
||||
while (itr.hasNext()) {
|
||||
multipartFile = request.getFile(itr.next());
|
||||
tmps.add(multipartFile);
|
||||
}
|
||||
map.put("filePath",tmps);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
public String saveFile(HttpServletRequest request, MultipartFile multipartFile, String fileType) throws Exception {
|
||||
String url = "";
|
||||
String tmpName = multipartFile.getOriginalFilename();// 完整路径 IE
|
||||
tmpName = tmpName.substring(tmpName.lastIndexOf("\\") + 1);
|
||||
tmpName = IdUtil.fastSimpleUUID() + tmpName;
|
||||
String imageFiles="/data/sz/zstp/" + fileType + "/";
|
||||
String os = System.getProperty("os.name");
|
||||
if(os.toLowerCase().startsWith("win")){
|
||||
imageFiles="D://files/" + fileType + "/";
|
||||
}
|
||||
String year = DateTimeHelper.getNowYear();
|
||||
String month = DateTimeHelper.getNowMonths();
|
||||
String day = DateTimeHelper.getNowDay();
|
||||
String specfile = imageFiles + year +"/" + month +"/"+ day;
|
||||
File file = new File(specfile + "/" + tmpName);
|
||||
|
||||
if (!file.getParentFile().exists()) {
|
||||
file.getParentFile().mkdirs();
|
||||
}
|
||||
url = "/" + fileType + "/" + year +"/" + month +"/"+ day + "/" + tmpName;
|
||||
if (!multipartFile.isEmpty()) {
|
||||
try {
|
||||
FileOutputStream fos = new FileOutputStream(file);
|
||||
InputStream in = multipartFile.getInputStream();
|
||||
byte[] bytes = new byte[1024];
|
||||
int len = 0;
|
||||
while ((len = in.read(bytes)) != -1) {
|
||||
fos.write(bytes, 0, len);
|
||||
}
|
||||
fos.close();
|
||||
in.close();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
private int getFileText(MultipartFile file) throws IOException {
|
||||
int length = 0;
|
||||
String fileName = file.getOriginalFilename();
|
||||
InputStream fileInputStream = file.getInputStream();
|
||||
try {
|
||||
ZipSecureFile.setMinInflateRatio(-1.0d);
|
||||
//获取文件后缀名
|
||||
String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
|
||||
//定义word内容
|
||||
String content = "";
|
||||
switch (suffix) {
|
||||
case "doc":
|
||||
WordExtractor wordExtractor = new WordExtractor(fileInputStream);
|
||||
content = wordExtractor.getText();
|
||||
break;
|
||||
case "docx":
|
||||
XWPFDocument document = new XWPFDocument(fileInputStream);
|
||||
XWPFWordExtractor extractor = new XWPFWordExtractor(document);
|
||||
content = extractor.getText();
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
//中文单词
|
||||
String cnWords = content.replaceAll("[^(\\u4e00-\\u9fa5,。《》?;’‘:“”【】、)(……¥!·)]", "");
|
||||
int cnWordsCount = cnWords.length();
|
||||
//非中文单词
|
||||
String noCnWords = content.replaceAll("[^(a-zA-Z0-9`\\-=\';.,/~!@#$%^&*()_+|}{\":><?\\[\\])]", " ");
|
||||
int noCnWordsCount = 0;
|
||||
String[] ss = noCnWords.split(" ");
|
||||
for (String s : ss) {
|
||||
if (s.trim().length() != 0) {
|
||||
noCnWordsCount++;
|
||||
}
|
||||
}
|
||||
length = cnWordsCount + noCnWordsCount;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
if (fileInputStream != null) {
|
||||
fileInputStream.close();
|
||||
}
|
||||
}
|
||||
return length;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,79 @@
|
|||
<?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.bonus.sgzb.system.mapper.FileInfoMapper">
|
||||
|
||||
<resultMap type="com.bonus.sgzb.system.domain.FileInfo" id="SysFileInfoResult">
|
||||
<result property="id" column="id" />
|
||||
<result property="modelId" column="model_id" />
|
||||
<result property="fileName" column="file_name" />
|
||||
<result property="fileUrl" column="file_url" />
|
||||
<result property="dicId" column="dic_id" />
|
||||
<result property="createBy" column="create_by" />
|
||||
<result property="createTime" column="create_time" />
|
||||
</resultMap>
|
||||
|
||||
<sql id="selectSysFileInfoVo">
|
||||
select id, model_id, file_name, file_url, dic_id, create_by, create_time from sys_file_info
|
||||
</sql>
|
||||
|
||||
<select id="selectSysFileInfoList" parameterType="com.bonus.sgzb.system.domain.FileInfo" resultMap="SysFileInfoResult">
|
||||
<include refid="selectSysFileInfoVo"/>
|
||||
<where>
|
||||
<if test="modelId != null "> and model_id = #{modelId}</if>
|
||||
<if test="fileName != null and fileName != ''"> and file_name like concat('%', #{fileName}, '%')</if>
|
||||
<if test="fileUrl != null and fileUrl != ''"> and file_url = #{fileUrl}</if>
|
||||
<if test="dicId != null "> and dic_id = #{dicId}</if>
|
||||
</where>
|
||||
</select>
|
||||
|
||||
<select id="selectSysFileInfoById" parameterType="Long" resultMap="SysFileInfoResult">
|
||||
<include refid="selectSysFileInfoVo"/>
|
||||
where id = #{id}
|
||||
</select>
|
||||
|
||||
<insert id="insertFileInfo" parameterType="com.bonus.sgzb.system.domain.FileInfo" useGeneratedKeys="true" keyProperty="id">
|
||||
insert into sys_file_info
|
||||
<trim prefix="(" suffix=")" suffixOverrides=",">
|
||||
<if test="modelId != null">model_id,</if>
|
||||
<if test="fileName != null">file_name,</if>
|
||||
<if test="fileUrl != null">file_url,</if>
|
||||
<if test="dicId != null">dic_id,</if>
|
||||
<if test="createBy != null">create_by,</if>
|
||||
<if test="createTime != null">create_time,</if>
|
||||
</trim>
|
||||
<trim prefix="values (" suffix=")" suffixOverrides=",">
|
||||
<if test="modelId != null">#{modelId},</if>
|
||||
<if test="fileName != null">#{fileName},</if>
|
||||
<if test="fileUrl != null">#{fileUrl},</if>
|
||||
<if test="dicId != null">#{dicId},</if>
|
||||
<if test="createBy != null">#{createBy},</if>
|
||||
<if test="createTime != null">#{createTime},</if>
|
||||
</trim>
|
||||
</insert>
|
||||
|
||||
<update id="updateSysFileInfo" parameterType="com.bonus.sgzb.system.domain.FileInfo">
|
||||
update sys_file_info
|
||||
<trim prefix="SET" suffixOverrides=",">
|
||||
<if test="modelId != null">model_id = #{modelId},</if>
|
||||
<if test="fileName != null">file_name = #{fileName},</if>
|
||||
<if test="fileUrl != null">file_url = #{fileUrl},</if>
|
||||
<if test="dicId != null">dic_id = #{dicId},</if>
|
||||
<if test="createBy != null">create_by = #{createBy},</if>
|
||||
<if test="createTime != null">create_time = #{createTime},</if>
|
||||
</trim>
|
||||
where id = #{id}
|
||||
</update>
|
||||
|
||||
<delete id="deleteSysFileInfoById" parameterType="Long">
|
||||
delete from sys_file_info where id = #{id}
|
||||
</delete>
|
||||
|
||||
<delete id="deleteSysFileInfoByIds" parameterType="String">
|
||||
delete from sys_file_info where id in
|
||||
<foreach item="id" collection="array" open="(" separator="," close=")">
|
||||
#{id}
|
||||
</foreach>
|
||||
</delete>
|
||||
</mapper>
|
||||
Loading…
Reference in New Issue