Commit 4a3fefdb by zhangkb

文件上传下载管理接口代码上传

parent 7b68fff7
package com.keymobile.indicators.api.uploadfile;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.keymobile.indicators.constant.Constants;
import com.keymobile.indicators.service.uploadfile.UploadFileService;
import com.keymobile.indicators.utils.LogManager;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@Api(tags={"文件管理功能"})
@RestController
@RequestMapping(value = "/fileManager")
public class UploadFileCtrl {
@Autowired
private UploadFileService uploadFileService;
@ApiOperation(value = "上传文件", notes = "上传文件")
@PostMapping(value = "/uploadFile")
public String uploadFile(@RequestParam MultipartFile mFile,@RequestParam String user,
@RequestParam String code) throws Exception{
//获取文件名和文件类型
if(mFile!=null) {
//获得文件名
String fileName = mFile.getOriginalFilename();
// 获取后缀
String fileType = null;
if(fileName.lastIndexOf(".")>=0) {
fileType = fileName.substring(fileName.lastIndexOf(".")+1);
fileName = fileName.substring(0,fileName.lastIndexOf(".")-1);
}
uploadFileService.uploadFile(mFile.getInputStream(), fileName, fileType, user, code);
LogManager.logInfo(Constants.LOG_INDICATOR_UPLOAD_FILE_API,"上传文件:{}",mFile.getOriginalFilename());
return "upload file success";
}else {
return "upload file is empty";
}
}
@ApiOperation(value = "下载文件", notes = "下载文件")
@GetMapping(value = "/downloadFile")
public void downloadFile(@RequestParam Integer id,HttpServletRequest request,
HttpServletResponse response)throws Exception{
uploadFileService.downloadFile(id, request, response);
}
@ApiOperation(value = "根据条件加载下载文件信息", notes = "根据条件加载下载文件信息")
@PostMapping(value = "/getByPageAndKeywordAndCode")
public Map<String,Object> getByPageAndKeywordAndCode(@RequestParam String code,
@RequestParam(required = false)String keyword,@RequestParam(defaultValue = "0")int page,
@RequestParam(defaultValue = "10")int rows)throws Exception{
return uploadFileService.getByPageAndKeywordAndCode(code, keyword, page, rows);
}
@ApiOperation(value = "批量删除文件信息", notes = "批量删除文件信息")
@PostMapping(value = "/deleteUploadFile")
public void deleteUploadFile(@RequestParam List<Integer> ids) {
uploadFileService.deleteUploadFile(ids);
}
}
......@@ -30,6 +30,8 @@ public class Constants {
public static final String LOG_INDICATOR_SHORTBOARD_TASK_API = "indicator.shortboardtask";
public static final String LOG_INDICATOR_UPLOAD_FILE_API = "indicator.uploadfile";
/** collection Name */
......
package com.keymobile.indicators.model.entity.uploadfile;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.Data;
/**
*author:zhangkb time:2020-9-25 desc:上传文件实体
*/
@Data
@Table(name="indi_upload_file")
public class UploadFile {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String fileName;//文件名
private String fileType;//文件类型
private String filePath;//文件上传保存路径
private String fileStatus;//上传文件情况:0:未可用 1:可用
private String uploadUser;//上传用户名
private String uploadDate;//上传时间
private String code;//机构编码
}
package com.keymobile.indicators.model.mapper.uploadfile;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import com.keymobile.indicators.model.entity.uploadfile.UploadFile;
import tk.mybatis.mapper.common.BaseMapper;
@Mapper
public interface UploadFileMapper extends BaseMapper<UploadFile>{
public int getByKeywordCount(Map<String,Object> param);
public List<UploadFile> getPageByKeywordAndCode(Map<String,Object> param);
public void deleteByIdIn(@Param("ids")List<Integer> ids);
}
package com.keymobile.indicators.service.uploadfile;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.keymobile.indicators.model.entity.uploadfile.UploadFile;
import com.keymobile.indicators.model.mapper.uploadfile.UploadFileMapper;
import com.keymobile.indicators.utils.DateUtils;
import com.keymobile.indicators.utils.FileUtils;
@Service
public class UploadFileService {
private Logger logger = LoggerFactory.getLogger(UploadFileService.class);
@Autowired
private UploadFileMapper uploadFileMapper;
@Value("${uploadfile.path}")
private String uploadFilePath;
//上传文件
public void uploadFile(InputStream in,String fileName,String fileType,
String user,String code) throws Exception{
//先保存文件详情到数据库中
UploadFile uploadFile = new UploadFile();
if(StringUtils.isNotBlank(fileType)) {
uploadFile.setFileName(fileName+"."+fileType);
uploadFile.setFileType(fileType);
}else {
uploadFile.setFileName(fileName);
}
uploadFile.setFileStatus("0");//标注未可用
uploadFile.setUploadUser(user);
uploadFile.setUploadDate(DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
uploadFile.setCode(code);
//保存
uploadFileMapper.insert(uploadFile);
//设置上传文件路径
StringBuilder filePath = new StringBuilder("");
if(StringUtils.isNotBlank(fileType)) {
filePath.append(uploadFilePath).append("/").append(fileName).append("-")
.append(uploadFile.getId()).append(".").append(fileType);
}else {
filePath.append(uploadFilePath).append("/").append(fileName).append("-")
.append(uploadFile.getId());
}
uploadFile.setFilePath(filePath.toString());
//上传文件到指定路径
FileUtils.uploadFile(in, filePath.toString());
uploadFile.setFileStatus("1");//可用
//修改上传文件路径和状态
uploadFileMapper.updateByPrimaryKey(uploadFile);
}
//下载文件
public void downloadFile(Integer id,HttpServletRequest request, HttpServletResponse response) throws Exception{
//根据id查找上传文件信息
UploadFile uploadFile = uploadFileMapper.selectByPrimaryKey(id);
if(uploadFile!=null) {
FileUtils.downloadFile(request, response, uploadFile.getFilePath());
}else {
logger.error("查找的上传文件不存在");
}
}
//加载上传文件列表
public Map<String,Object> getByPageAndKeywordAndCode(String code,String keyword,
int page,int rows)throws Exception{
Map<String,Object> resultMap = new HashMap<>();
Map<String,Object> paramMap = new HashMap<>();
paramMap.put("code", code);
if(StringUtils.isBlank(keyword)) {
paramMap.put("keyword", null);
}else {
paramMap.put("keyword", "%"+keyword+"%");
}
//计算总数
int count = uploadFileMapper.getByKeywordCount(paramMap);
//计算start
int start = page*rows;
paramMap.put("start", start);
paramMap.put("end", rows);
List<UploadFile> resultList = uploadFileMapper.getPageByKeywordAndCode(paramMap);
resultMap.put("resultList", resultList);
resultMap.put("total", count);
return resultMap;
}
//批量删除上传文件数据
public void deleteUploadFile(List<Integer> ids) {
uploadFileMapper.deleteByIdIn(ids);
}
}
package com.keymobile.indicators.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FileUtils {
private static Logger logger = LoggerFactory.getLogger(FileUtils.class);
/**
* 上传文件到指定路径
* @param mFile 要上传的文件
* @param path 指定路径
*/
public static void uploadFile(/**MultipartFile mFile*/InputStream in, String path) throws Exception{
try {
byte[] buffer = new byte[1024];
int len = 0;
File file = new File(path);
File fileParent = file.getParentFile();
if (!fileParent.exists()) {
fileParent.mkdirs();
}
OutputStream out = new FileOutputStream(path);
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.close();
in.close();
} catch (Exception e) {
logger.error(path +"文件上传失败:", e);
throw new Exception(path +"文件上传失败:"+e);
}
}
/*
* 针对不同浏览器下载文件名乱码
* 根据文件所在路径下载文件
*/
public static void downloadFile(HttpServletRequest request, HttpServletResponse response, String filePath)throws Exception{
File file = new File(filePath);
//取得文件名
String fileName = file.getName();
InputStream fis = null;
try {
fis = new FileInputStream(file);
request.setCharacterEncoding("UTF-8");
String agent = request.getHeader("User-Agent").toUpperCase();
if ((agent.indexOf("MSIE") > 0) || ((agent.indexOf("RV") != -1) && (agent.indexOf("FIREFOX") == -1)))
fileName = URLEncoder.encode(fileName, "UTF-8");
else {
fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
}
response.reset();
response.setCharacterEncoding("UTF-8");
response.setContentType("application/octet-stream");
response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
response.setHeader("Content-Length", String.valueOf(file.length()));
byte[] b = new byte[1024];
int len;
while ((len = fis.read(b)) != -1) {
response.getOutputStream().write(b, 0, len);
}
response.flushBuffer();
fis.close();
}catch (Exception e) {
logger.error("文件下载失败:", e);
throw new Exception("文件下载失败:"+e);
}
}
}
......@@ -11,7 +11,9 @@ public enum ModelPathEnum {
LOG_INDICATOR_PARAMETER_API("indicator.parameter","台账管理"),
LOG_INDICATOR_BASEDATACHECK("indicator.basedatacheck","数据项稽核"),
LOG_INDICATOR_SHORTBOARD_UNIT_API("indicator.shortboardunit","短板管理/短板规则"),
LOG_INDICATOR_SHORTBOARD_TASK_API("indicator.shortboardtask","短板管理/短板清单");
LOG_INDICATOR_SHORTBOARD_TASK_API("indicator.shortboardtask","短板管理/短板清单"),
LOG_INDICATOR_UPLOAD_FILE_API("indicator.uploadfile","文件管理");
private String modelName;
private String modelPath;
......
......@@ -64,3 +64,6 @@ logging:
level:
com.keymobile.indicators: info
config: classpath:logback-custom.xml
uploadfile:
path: /home/uploadfile
\ No newline at end of file
......@@ -51,6 +51,9 @@
<logger name="indicator.shortboardtask">
<appender-ref ref="db" />
</logger>
<logger name="indicator.uploadfile">
<appender-ref ref="db" />
</logger>
<root level="INFO">
<appender-ref ref="stdout" />
</root>
......
<?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.keymobile.indicators.model.mapper.uploadfile.UploadFileMapper">
<select id="getPageByKeywordAndCode" parameterType="map" resultType="com.keymobile.indicators.model.entity.uploadfile.UploadFile" >
select *
from indi_upload_file
where
file_status="1" and
code = #{code}
<if test="keyword!=null">
and file_name like #{keyword}
</if>
order by upload_date desc
limit #{start},#{end}
</select>
<select id="getByKeywordCount" parameterType="map" resultType="java.lang.Integer">
select count(1)
from indi_upload_file
where
file_status="1" and
code = #{code}
<if test="keyword!=null">
and file_name like #{keyword}
</if>
</select>
<delete id="deleteByIdIn" parameterType="java.util.List">
delete
from indi_upload_file
where id in
<foreach item="id" collection="ids" open="(" close=")" separator=",">
#{id}
</foreach>
</delete>
</mapper>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment