Commit 7d187bb8 by Java-聂换换

举报

parent 5e005fa9
...@@ -37,6 +37,9 @@ ...@@ -37,6 +37,9 @@
<dozer.version>5.5.1</dozer.version> <dozer.version>5.5.1</dozer.version>
<poi.version>3.9</poi.version> <poi.version>3.9</poi.version>
<freemarker.version>2.3.20</freemarker.version> <freemarker.version>2.3.20</freemarker.version>
<!-- Spring Swagger -->
<swagger.version>2.6.1</swagger.version>
<swagger-annotations.version>1.5.16</swagger-annotations.version>
<!-- jdbc driver setting --> <!-- jdbc driver setting -->
<mysql.driver.version>5.1.30</mysql.driver.version> <mysql.driver.version>5.1.30</mysql.driver.version>
<oracle.driver.version>10.2.0.4.0</oracle.driver.version> <oracle.driver.version>10.2.0.4.0</oracle.driver.version>
...@@ -154,6 +157,7 @@ ...@@ -154,6 +157,7 @@
<artifactId>spring-jdbc</artifactId> <artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version> <version>${spring.version}</version>
</dependency> </dependency>
<!-- bean validate --> <!-- bean validate -->
<dependency> <dependency>
<groupId>org.hibernate</groupId> <groupId>org.hibernate</groupId>
...@@ -261,6 +265,18 @@ ...@@ -261,6 +265,18 @@
<version>2.1</version> <version>2.1</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<!--io-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.swagger/swagger-annotations -->
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>${swagger-annotations.version}</version>
</dependency>
<!-- <dependency> <!-- <dependency>
<groupId>javax.servlet</groupId> <groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId> <artifactId>javax.servlet-api</artifactId>
......
...@@ -26,4 +26,13 @@ public class ErrorCode { ...@@ -26,4 +26,13 @@ public class ErrorCode {
public static final String STATUS_CODE_4104 = "4104";// 校验码错误 public static final String STATUS_CODE_4104 = "4104";// 校验码错误
public static final String STATUS_CODE_4105 = "4105";// 校验码已失效 public static final String STATUS_CODE_4105 = "4105";// 校验码已失效
public static final String STATUS_CODE_4106 = "4106";// 需要重新登录 public static final String STATUS_CODE_4106 = "4106";// 需要重新登录
/*文件上传模块*/
public static final String NO_FILE_UPLOADED = "6001";
public static final String NO_FILE_FOUND_DESC = "no file found";
public static final String WRITE_FILE_FAIL = "6002";
public static final String WRITE_FILE_FAIL_DESC = "fail to write file on disk";
/**数据库**/
public static final String SQL_ERROR= "5001";
} }
package com.ejweb.modules.front.report.api;
import com.ejweb.conf.ErrorCode;
import com.ejweb.core.api.ResponseBean;
import com.ejweb.modules.front.report.bean.FrontReportBean;
import com.ejweb.modules.front.report.entity.Captcha;
import com.ejweb.modules.front.report.service.FrontReportService;
import com.ejweb.modules.front.report.utils.CaptchaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by lenovo on 2017/9/7.
*/
@RestController
@RequestMapping("/front/report")
public class FrontReportController {
@Autowired
private FrontReportService frontReportService;
/**
* 获取验证码的code值
* @return
*/
@RequestMapping("captchaCode")
public ResponseBean captchaCode() {
ResponseBean response = new ResponseBean();
Captcha captcha = new Captcha();
captcha.setCode(CaptchaUtil.getCaptchaCode());
response.setData(captcha);
return response;
}
@RequestMapping("addReport")
public ResponseBean addReport(FrontReportBean bean){
ResponseBean responseBean = new ResponseBean();
if(bean!=null){
return frontReportService.addReport(bean);
}
responseBean.setStatus(ErrorCode.STATUS_CODE_4001);
responseBean.setMessage("接收参数失败");
return responseBean;
}
}
package com.ejweb.modules.front.report.bean;
import com.ejweb.core.base.BaseBean;
import java.util.List;
/**
* Created by lenovo on 2017/9/8.
*/
public class FrontReportBean extends BaseBean{
private String id;
private String reportProject; //varchar(255) NOT NULL COMMENT '被举报项目',
private String reportCity; //varchar(255) NOT NULL COMMENT '所在城市',
private String reportTime; //varchar(20) NOT NULL COMMENT '举报时间',
private String reportContent; //text NOT NULL COMMENT '举报内容',
private String reportPersonName; //varchar(255) NOT NULL COMMENT '举报人姓名',
private String reportPersonTel; //varchar(255) NOT NULL COMMENT '举报人电话',
private String reportPersonEmail; //varchar(255) NOT NULL COMMENT '举报人邮箱',
private String reportSource; //varchar(255) NOT NULL COMMENT '举报途径 web:官网 oa:融创OA系统 supplier:供应商系统 wechat:微信公众号 sunacE:融E offline:线下扫码 tel:电话 email:邮件 visit:来访',
private String reportStatus; //varchar(1) DEFAULT NULL COMMENT '举报状态 0 未处理 1 处理中 2 已处理',
private String supplementCompany; //varchar(255) DEFAULT NULL COMMENT '被举报公司',
private String supplementDepartment; //varchar(255) DEFAULT NULL COMMENT '被举报部门',
private String supplementInformant; //varchar(255) DEFAULT NULL COMMENT '被举报人',
private String supplementTitle; //varchar(255) DEFAULT NULL COMMENT '标题',
private String supplementType; //varchar(255) DEFAULT NULL COMMENT '业务类型 1 营销 2 工程 3 成本 4 招采 5人力 6物业 7投诉',
private String supplementArea; //varchar(255) DEFAULT NULL COMMENT '被举报区域',
private String supplementProject; //varchar(255) DEFAULT NULL COMMENT '被举报项目',
private String supplementContent; //text,
private String dealPersonName; //varchar(255) DEFAULT NULL COMMENT '处理人',
private String dealResult; //varchar(255) DEFAULT NULL COMMENT '处理结论 1 投诉 2 举报无效 3 举报属实',
private String exchangeBeforeUser; //varchar(255) DEFAULT NULL COMMENT '移交/转交前用户id',
private String exchangeAfterUser; //varchar(255) DEFAULT NULL COMMENT '移交/转交后用户id(只记录最新的移交用户,此处不记录历史)',
private List<ReportAttachmentBean> reportAttachmentList; // 附件
public String getReportProject() {
return reportProject;
}
public void setReportProject(String reportProject) {
this.reportProject = reportProject;
}
public String getReportCity() {
return reportCity;
}
public void setReportCity(String reportCity) {
this.reportCity = reportCity;
}
public String getReportTime() {
return reportTime;
}
public void setReportTime(String reportTime) {
this.reportTime = reportTime;
}
public String getReportContent() {
return reportContent;
}
public void setReportContent(String reportContent) {
this.reportContent = reportContent;
}
public String getReportPersonName() {
return reportPersonName;
}
public void setReportPersonName(String reportPersonName) {
this.reportPersonName = reportPersonName;
}
public String getReportPersonTel() {
return reportPersonTel;
}
public void setReportPersonTel(String reportPersonTel) {
this.reportPersonTel = reportPersonTel;
}
public String getReportPersonEmail() {
return reportPersonEmail;
}
public void setReportPersonEmail(String reportPersonEmail) {
this.reportPersonEmail = reportPersonEmail;
}
public String getReportSource() {
return reportSource;
}
public void setReportSource(String reportSource) {
this.reportSource = reportSource;
}
public String getReportStatus() {
return reportStatus;
}
public void setReportStatus(String reportStatus) {
this.reportStatus = reportStatus;
}
public String getSupplementCompany() {
return supplementCompany;
}
public void setSupplementCompany(String supplementCompany) {
this.supplementCompany = supplementCompany;
}
public String getSupplementDepartment() {
return supplementDepartment;
}
public void setSupplementDepartment(String supplementDepartment) {
this.supplementDepartment = supplementDepartment;
}
public String getSupplementInformant() {
return supplementInformant;
}
public void setSupplementInformant(String supplementInformant) {
this.supplementInformant = supplementInformant;
}
public String getSupplementTitle() {
return supplementTitle;
}
public void setSupplementTitle(String supplementTitle) {
this.supplementTitle = supplementTitle;
}
public String getSupplementType() {
return supplementType;
}
public void setSupplementType(String supplementType) {
this.supplementType = supplementType;
}
public String getSupplementArea() {
return supplementArea;
}
public void setSupplementArea(String supplementArea) {
this.supplementArea = supplementArea;
}
public String getSupplementProject() {
return supplementProject;
}
public void setSupplementProject(String supplementProject) {
this.supplementProject = supplementProject;
}
public String getSupplementContent() {
return supplementContent;
}
public void setSupplementContent(String supplementContent) {
this.supplementContent = supplementContent;
}
public String getDealPersonName() {
return dealPersonName;
}
public void setDealPersonName(String dealPersonName) {
this.dealPersonName = dealPersonName;
}
public String getDealResult() {
return dealResult;
}
public void setDealResult(String dealResult) {
this.dealResult = dealResult;
}
public String getExchangeBeforeUser() {
return exchangeBeforeUser;
}
public void setExchangeBeforeUser(String exchangeBeforeUser) {
this.exchangeBeforeUser = exchangeBeforeUser;
}
public String getExchangeAfterUser() {
return exchangeAfterUser;
}
public void setExchangeAfterUser(String exchangeAfterUser) {
this.exchangeAfterUser = exchangeAfterUser;
}
public List<ReportAttachmentBean> getReportAttachmentList() {
return reportAttachmentList;
}
public void setReportAttachmentList(List<ReportAttachmentBean> reportAttachmentList) {
this.reportAttachmentList = reportAttachmentList;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
package com.ejweb.modules.front.report.dao;
import com.ejweb.core.persistence.CrudDao;
import com.ejweb.modules.front.report.bean.FrontReportBean;
import com.ejweb.modules.front.report.bean.ReportAttachmentBean;
import com.ejweb.modules.front.report.entity.FrontReportEntity;
/**
* Created by lenovo on 2017/9/8.
*/
public interface FrontReportDao extends CrudDao<FrontReportEntity> {
// 添加举报信息
public Integer insertReport(FrontReportBean bean);
// 添加举报附件
public Integer insertReportAttachment(ReportAttachmentBean bean);
}
package com.ejweb.modules.front.report.entity;
/**
* Created by BrianHolsen on 2017-08-08 at 15:37.
*/
public class Captcha {
private String code;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
package com.ejweb.modules.front.report.entity;
import com.ejweb.core.persistence.DataEntity;
/**
* Created by lenovo on 2017/9/8.
*/
public class FrontReportEntity extends DataEntity<FrontReportEntity> {
}
package com.ejweb.modules.front.report.service;
import com.ejweb.conf.ErrorCode;
import com.ejweb.conf.GConstants;
import com.ejweb.core.api.ResponseBean;
import com.ejweb.core.service.CrudService;
import com.ejweb.core.utils.IdWorker;
import com.ejweb.modules.front.report.bean.FrontReportBean;
import com.ejweb.modules.front.report.bean.ReportAttachmentBean;
import com.ejweb.modules.front.report.dao.FrontReportDao;
import com.ejweb.modules.front.report.entity.FrontReportEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* Created by lenovo on 2017/9/8.
*/
@Service
@Transactional(readOnly = true)
public class FrontReportService extends CrudService<FrontReportDao,FrontReportEntity>{
// 添加举报信息
@Transactional(readOnly = false)
public ResponseBean addReport(FrontReportBean bean){
ResponseBean responseBean = new ResponseBean();
bean.setId(IdWorker.getNextId("R"));
// 添加举报信息表
int row = dao.insertReport(bean);
if(row == 1){ // 添加成功
List<ReportAttachmentBean> list = bean.getReportAttachmentList();
if(list != null && list.size()>0){ // 添加举报附件
for(ReportAttachmentBean reportAttachmentBean:list){
reportAttachmentBean.setReportId(bean.getId());
reportAttachmentBean.setId(IdWorker.getNextId("RA"));
dao.insertReportAttachment(reportAttachmentBean);
}
}
responseBean.setStatus(ErrorCode.STATUS_CODE_2000);
responseBean.setMessage(GConstants.OK);
return responseBean;
}
responseBean.setStatus(ErrorCode.SQL_ERROR);
responseBean.setMessage("数据添加失败");
return responseBean;
}
}
package com.ejweb.modules.front.report.servlet;
import com.ejweb.modules.front.report.utils.CaptchaUtil;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.geom.Line2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.Random;
/**
* Created by BrianHolsen on 2017-08-08 at 11:42.
*/
public class CaptchaServlet extends HttpServlet {
private static final long serialVersionUID = 1325598241;
private int height = 25;
private int width = 90;
public CaptchaServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String ch = CaptchaUtil.getCaptcha(request.getParameter("code"));
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Max-Age", 0);
Random r = new Random(new Date().getTime());
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = image.createGraphics();
graphics2D.setColor(new Color(192, 192, 192)); // or the background color u want
graphics2D.fillRect(0, 0, width, height);
for (int i = 0; i < 20; i++) {
Line2D line1 = new Line2D.Float(Math.abs(r.nextInt()) % width, Math.abs(r.nextInt()) % height
, Math.abs(r.nextInt()) % width, Math.abs(r.nextInt()) % height);
graphics2D.setPaint(new GradientPaint(30, 30, new Color(Math.abs(r.nextInt())), 15, 25, new Color(Math.abs(r.nextInt()))));
graphics2D.draw(line1);
}
graphics2D.setPaint(new GradientPaint(30, 30, Color.BLUE, 15, 25, Color.RED, true));
Font font = new Font("Verdana", Font.CENTER_BASELINE, 20);
graphics2D.setFont(font);
graphics2D.drawString(ch, 5, 20);
graphics2D.dispose();
OutputStream outputStream = response.getOutputStream();
ImageIO.write(image, "jpeg", outputStream);
outputStream.close();
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
package com.ejweb.modules.front.report.utils;
import java.io.UnsupportedEncodingException;
import java.security.InvalidParameterException;
import java.util.Date;
import java.util.Random;
/**
* Created by BrianHolsen on 2017-08-08 at 13:35.
*/
public class CaptchaUtil {
private static byte[] KEY = {0x70, 0x3f, 0x2b, 0x47};
private static final char[] HEX_TABLE_LOWER_CASE = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f'};
private static int LEN = 6;
private static int EXPIRE_MININUTES = 3;
/**
*
* @param str
* @return
*/
private static String encrypt(String str) {
if (null == str || str.equals("")) {
return str;
}
Random rand = new Random(new Date().getTime());
try {
StringBuffer buffer = new StringBuffer();
buffer.append(Math.abs(rand.nextInt()) % 10);
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
buffer.append(c);
for (int j = 0; j < c % 5; j++) {
buffer.append(Math.abs(rand.nextInt()) % 10);
}
}
byte[] bts = buffer.toString().getBytes("utf-8");
for (int i = 0; i < bts.length; i++) {
bts[i] ^= KEY[i % KEY.length];
}
return toHexString(bts);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return str;
}
private static String decrypt(String str) {
if (null == str || str.equals("")) {
return str;
}
byte[] bts = toByteArrayFromHexString(str);
for (int i = 0; i < bts.length; i++) {
bts[i] ^= KEY[i % KEY.length];
}
StringBuffer buffer = new StringBuffer();
for (int i = 1; i < bts.length; i++) {
buffer.append((char) bts[i]);
i += bts[i] % 5;
}
return buffer.toString();
}
private static String toHexString(int data) {
StringBuffer buf = new StringBuffer();
char[] hex_table = HEX_TABLE_LOWER_CASE;
int index8 = (data >> 28) & 0x0000000F;
int index7 = (data >> 24) & 0x0000000F;
int index6 = (data >> 20) & 0x0000000F;
int index5 = (data >> 16) & 0x0000000F;
int index4 = (data >> 12) & 0x0000000F;
int index3 = (data >> 8) & 0x0000000F;
int index2 = (data >> 4) & 0x0000000F;
int index1 = data & 0x0000000F;
buf.append(hex_table[index8])
.append(hex_table[index7])
.append(hex_table[index6])
.append(hex_table[index5])
.append(hex_table[index4])
.append(hex_table[index3])
.append(hex_table[index2])
.append(hex_table[index1]);
return buf.toString();
}
private static String toHexString(byte[] data) {
StringBuffer buf = new StringBuffer();
char[] hex_table = HEX_TABLE_LOWER_CASE;
for (int i = 0; i < data.length; i++) {
int index_low = data[i] & 0x0F;
int index_high = (data[i] >> 4) & 0x0F;
buf.append(hex_table[index_high]).append(hex_table[index_low]);
}
return buf.toString();
}
private static byte[] toByteArrayFromHexString(String hexString) {
if (hexString.length() % 2 != 0) {
throw new InvalidParameterException("The length of a hex string must be even");
}
hexString = hexString.toLowerCase();
byte[] bts = hexString.getBytes();
int startIndex = 0;
if (bts[0] == '0' && (bts[1] == 'x')) {
startIndex = 2;
}
byte[] result = new byte[(bts.length - startIndex) / 2];
for (int i = startIndex; i < bts.length; i += 2) {
byte high = bts[i];
byte low = bts[i + 1];
if ((high < '0' || (high > '9' && high < 'a') || high > 'f')
|| (low < '0' || (low > '9' && low < 'a') || low > 'f')) {
throw new InvalidParameterException("Invalid char(s) in hex string");
}
high -= 48;
low -= 48;
if (high > 10) {
high -= 39;
}
if (low > 10) {
low -= 39;
}
result[(i - startIndex) / 2] = (byte) ((high << 4) + low);
}
return result;
}
public static boolean validate(String captcha, String code) {
if (captcha == null || captcha.equals("") || code == null || code.equals("")) {
return false;
}
try {
String data = decrypt(code);
String correctCaptcha = data.substring(0, LEN);
long time = new Date().getTime();
long expires = Long.parseLong(data.substring(LEN));
if (captcha.equals(correctCaptcha) && expires > time) {
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
*
* 获取验证码对应的code值
* @return
*/
public static String getCaptchaCode() {
Random rand = new Random(new Date().getTime());
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < LEN; i++) {
buffer.append(Math.abs(rand.nextInt()) % 10);
}
//System.out.println(buffer.toString());
buffer.append(new Date().getTime() + EXPIRE_MININUTES * 60 * 1000);
//buffer.append(new Date().getTime() + 30 * 1000);
//System.out.println(buffer.toString());
return CaptchaUtil.encrypt(buffer.toString());
}
public static String getCaptcha(String code) {
if (code == null || code.equals("")) {
return "";
}
try {
String data = decrypt(code);
String correctCaptcha = data.substring(0, LEN);
return correctCaptcha;
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public static void main(String[] args) throws InterruptedException {
String code = getCaptchaCode();
System.out.println(code);
String captcha = getCaptcha(code);
System.out.println(captcha);
System.out.println(validate(captcha, code));
Thread.sleep(2000);
System.out.println(validate(captcha, code));
Thread.sleep(3000);
System.out.println(validate(captcha, code));
// System.out.println(CaptchaUtil.encrypt(buffer.toString()));
}
}
package com.ejweb.modules.front.upload.api;
import com.ejweb.conf.ErrorCode;
import com.ejweb.conf.GConstants;
import com.ejweb.core.api.ResponseBean;
import com.ejweb.modules.sys.service.LogService;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
;
/**
* Created by BrianHolsen on 2017-07-11 at 17:19.
*/
@RequestMapping("/front/file")
public class FileController {
private class UploadResultBean {
public String uri;
public int size;
public String extention;
public String fileName;
}
// <editor-fold desc="<===private fields=========================================================================>">
@Autowired
private LogService logService;
private static final String savePath = GConstants.getValue("file.upload.dir");
private static final String pathSeparator = GConstants.getValue("upload.path.separator", "\\");
private static final String allowedExt = GConstants.getValue("upload.extension", "");
private String downloadFileMethodName = "downloadFile";
private String downloadFileParamName = "file";
private String downloadImageMethodName = "downloadImage";
private String downloadImageParamName = "file";
private String viewServer = GConstants.getValue("file.prefix.url","http://59.110.18.103:8089");
// </editor-fold>
// <editor-fold desc="<===getters & setters======================================================================>">
public String getDownloadFileMethodName() {
return downloadFileMethodName;
}
public void setDownloadFileMethodName(String downloadFileMethodName) {
this.downloadFileMethodName = downloadFileMethodName;
}
public String getDownloadFileParamName() {
return downloadFileParamName;
}
public void setDownloadFileParamName(String downloadFileParamName) {
this.downloadFileParamName = downloadFileParamName;
}
public String getDownloadImageMethodName() {
return downloadImageMethodName;
}
public void setDownloadImageMethodName(String downloadImageMethodName) {
this.downloadImageMethodName = downloadImageMethodName;
}
public String getDownloadImageParamName() {
return downloadImageParamName;
}
public void setDownloadImageParamName(String downloadImageParamName) {
this.downloadImageParamName = downloadImageParamName;
}
// </editor-fold>
public ResponseBean upload(HttpServletRequest request) {
ResponseBean response = new ResponseBean();
boolean isMutipart = ServletFileUpload.isMultipartContent(request);
if (isMutipart) {
String currentUri = request.getRequestURI();
int index = currentUri.lastIndexOf("/");
String baseUri = currentUri.substring(0, index);
FileItemFactory factory = new org.apache.commons.fileupload.disk.DiskFileItemFactory();
ServletFileUpload fileUpload = new ServletFileUpload(factory);
try {
List<FileItem> fileItems = fileUpload.parseRequest(request);
if (fileItems.size() < 1) {
response.setStatus(ErrorCode.NO_FILE_UPLOADED);
response.setMessage(ErrorCode.NO_FILE_FOUND_DESC);
} else if (fileItems.size() == 1) {
FileItem item = fileItems.get(0);
UploadResultBean resultBean = this.storeFile(item.getName(), baseUri, item.get());
if (resultBean == null) {
response.setStatus(ErrorCode.WRITE_FILE_FAIL);
response.setMessage(ErrorCode.WRITE_FILE_FAIL_DESC);
} else {
response.setData(resultBean);
}
} else {
List<UploadResultBean> beans = new ArrayList<>();
for (FileItem item : fileItems) {
if(!item.isFormField()){
UploadResultBean resultBean = this.storeFile(item.getName(), baseUri, item.get());
beans.add(resultBean);
}
}
response.setData(beans);
}
} catch (FileUploadException e) {
//this.logService.logError(e.getMessage());
e.printStackTrace();
}
}
return response;
}
public void downloadFile(HttpServletRequest request, HttpServletResponse response, String file) {
if (file == null || file.isEmpty()) {
response.setStatus(HttpStatus.NOT_FOUND.value());
}
byte[] bts = this.getFile(file);
if (bts == null) {
response.setStatus(HttpStatus.NOT_FOUND.value());
}
response.setContentType("application/force-download");
response.setContentLength(bts.length);
response.setHeader("Content-Transfer-Encoding", "binary");
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Content-Disposition", "attachment; filename=\"" + file + "\"");
OutputStream outputStream = null;
try {
outputStream = response.getOutputStream();
outputStream.write(bts);
} catch (IOException e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(outputStream);
}
}
@ResponseBody
public byte[] downloadImage(String file) {
return this.getFile(file);
}
// <editor-fold desc="<===private methods========================================================================>">
private UploadResultBean storeFile(String name, String baseUri, byte[] bts) {
UploadResultBean bean = new UploadResultBean();
// String id = UUIDUtil.uuid();
bean.extention = this.getExtension(name);
bean.size = bts.length;
bean.fileName = name;
String pathRel = this.getStoreRefDir() + name;
File file = new File(this.savePath + pathSeparator + pathRel);
try {
FileUtils.writeByteArrayToFile(file, bts);
} catch (IOException e) {
//this.logService.logError(e.getMessage());
e.printStackTrace();
return null;
}
String method = "";
String param = "";
switch (bean.extention.trim().toLowerCase()) {
case ".bmp":
case ".jpg":
case ".jpeg":
case ".png":
case ".gif":
method = this.getDownloadImageMethodName();
param = this.getDownloadImageParamName();
if (method == null || method.isEmpty()) {
method = "downloadImage";
}
if (param == null || param.isEmpty()) {
param = "file";
}
break;
default:
method = this.getDownloadFileMethodName();
param = this.getDownloadFileParamName();
if (method == null || method.isEmpty()) {
method = "downloadFile";
}
if (param == null || param.isEmpty()) {
param = "file";
}
break;
}
bean.uri =viewServer + baseUri + "/" + method + "?" + param + "=" + pathRel.replace(this.pathSeparator, "_");
return bean;
}
private byte[] getFile(String name) {
String path = this.savePath + this.pathSeparator + name.replace("_", this.pathSeparator);
try {
byte[] bts = FileUtils.readFileToByteArray(new File(path));
return bts;
} catch (IOException e) {
//this.logService.logError(e.getMessage());
e.printStackTrace();
return null;
}
}
private String getStoreRefDir() {
// SimpleDateFormat df = new SimpleDateFormat("yyyy" + pathSeparator + "MM" + pathSeparator + "dd");
// String str = df.format(new Date()) + this.pathSeparator;
return "";
}
private String getExtension(String name) {
if (name == null || name.isEmpty()) {
return "";
}
int index = name.lastIndexOf(".");
if (index > 0) {
return name.substring(index);
}
return "";
}
// </editor-fold>
}
\ No newline at end of file
package com.ejweb.modules.front.upload.api;
import com.alibaba.fastjson.JSON;
import com.ejweb.conf.ErrorCode;
import com.ejweb.conf.GConstants;
import com.ejweb.core.api.RequestBean;
import com.ejweb.core.api.ResponseBean;
import com.ejweb.core.util.Util;
import com.ejweb.core.utils.IdWorker;
import com.ejweb.modules.front.upload.bean.FileBean;
import com.ejweb.modules.front.upload.bean.UploadBean;
import com.ejweb.modules.front.upload.bean.UploadFileBean;
import com.ejweb.modules.front.upload.service.FrontUploadService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
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.commons.CommonsMultipartFile;
import sun.misc.BASE64Decoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @team IT Team
* @author renmb
* @version 1.0
* @time 2016-03-22
*
*/
@Controller
@RequestMapping(value = "/front/api/upload")
class FrontUploadController {
@Autowired
private FrontUploadService frontUploadService;
/**
* 使用BASE64上传文件
*
* @author renmb
* @time 2016年11月1日
* @param request
* @param requestBean
* @return
*/
@ApiOperation(value = "BASE64文件上传", httpMethod = "POST", response = ResponseBean.class, notes = "使用BASE64上传文件", position = 1)
@ResponseBody
@RequestMapping(value="/base64", method ={RequestMethod.POST}, produces={MediaType.APPLICATION_JSON_VALUE})
public ResponseBean base64(HttpServletRequest request, RequestBean requestBean) {
ResponseBean responseBean = new ResponseBean();
List<UploadFileBean> uploadFiles = null;
// String clientip = Util.getOnlineIP(request);
UploadBean uploadFile = null;
uploadFile = JSON.parseObject(requestBean.getContent(), UploadBean.class);
String clientip = StringUtils.isEmpty(uploadFile.getClientip()) ? Util.getOnlineIP(request)
: uploadFile.getClientip();
String message = frontUploadService.validate(uploadFile);
if (message == null) {
uploadFiles = new ArrayList<UploadFileBean>(6);
// uploadFile.setFiles(uploadFiles);
List<UploadFileBean> files = uploadFile.getFiles();
if (files == null || files.size() == 0) {
responseBean.setStatus(ErrorCode.STATUS_CODE_4001);
responseBean.setMessage("获取不到文件列表!");
return responseBean;
}
// 生成本次会话的随机数随机数
String sessionId = IdWorker.getNextId();
for (UploadFileBean file : files) {// 遍历所有提交的文件
try {
String originalFilename = file.getName();
if (StringUtils.isBlank(originalFilename))
originalFilename = "base64.png";
if (StringUtils.isNotBlank(originalFilename)) {// 文件扩展名称不能为NULL
if (originalFilename.contains("%") || originalFilename.contains(";")) {
responseBean.setStatus(ErrorCode.STATUS_CODE_4001);
responseBean.setMessage("上传文件不允许含有非法字符,请改正!");
return responseBean;
}
}
if (StringUtils.isNotBlank(file.getData())) {// 文件扩展名称不能为NULL
file.setData(file.getData().replaceAll("data:image/jpeg;base64,", ""));
BASE64Decoder decoder = new BASE64Decoder();
byte[] buf = decoder.decodeBuffer(file.getData());
for (int i = 0, len = buf.length; i < len; ++i) {
if (buf[i] < 0) {// 调整异常数据
buf[i] += 256;
}
}
InputStream in = new ByteArrayInputStream(buf);
UploadFileBean fileBean = frontUploadService.addUploadFile(sessionId, in, file.getName(),
originalFilename, "image/png", uploadFile.getModule(), uploadFile.getAppCode(), clientip,uploadFile.getOrientataion());
fileBean.setOrientataion(uploadFile.getOrientataion());
uploadFiles.add(fileBean);
}
} catch (Exception e) {
// TODO: handle exception
}
}
}
if (uploadFiles == null || uploadFiles.size() == 0) {
responseBean.setStatus(ErrorCode.STATUS_CODE_4001);
responseBean.setMessage("获取不到文件列表!");
return responseBean;
}
uploadFile.setFiles(uploadFiles);
uploadFile.setSize(uploadFiles.size());
uploadFile.setUrl(GConstants.FILE_PREFIX_URL);
responseBean.setStatus(ErrorCode.STATUS_CODE_2000);
responseBean.setMessage(GConstants.OK);
responseBean.setData(uploadFile);
return responseBean;
}
@ApiOperation(value = "15.1 文件上传接口1", httpMethod = "POST", response = ResponseBean.class, notes = "批量文件上传", position = 1)
@ResponseBody
@RequestMapping(value="/files", method ={RequestMethod.POST}, produces={MediaType.APPLICATION_JSON_VALUE})
public ResponseBean files(HttpServletRequest request, @RequestParam("file") CommonsMultipartFile[] files,
RequestBean requestBean) {
ResponseBean responseBean = new ResponseBean();
List<UploadFileBean> uploadFiles = null;
String clientip = Util.getOnlineIP(request);
UploadBean uploadFile = null;
uploadFile = JSON.parseObject(requestBean.getContent(), UploadBean.class);
// for (CommonsMultipartFile file : files) {// 遍历文件名,含有非法字符提示错误
//
// String originalFilename = file.getOriginalFilename();
// if (StringUtils.isNotBlank(originalFilename)) {// 文件扩展名称不能为NULL
// if (originalFilename.contains("%") || originalFilename.contains(";")) {
// responseBean.setStatus(ErrorCode.STATUS_CODE_4001);
// responseBean.setMessage("上传文件不允许含有非法字符,请改正!");
// return responseBean;
// }
// }
// }
// String message = uploadService.check(files, uploadFile, clientip);
// if (StringUtils.isNotEmpty(message)) {
// responseBean.setStatus(ErrorCode.STATUS_CODE_4001);
// responseBean.setMessage(message);
// return responseBean;
// }
uploadFiles = frontUploadService.addMultipartFile(files, uploadFile, clientip);
if (uploadFiles == null || uploadFiles.size() == 0) {
responseBean.setStatus(ErrorCode.STATUS_CODE_4001);
responseBean.setMessage("获取不到文件列表!");
return responseBean;
}
uploadFile.setSize(uploadFiles.size());
uploadFile.setUrl(GConstants.FILE_PREFIX_URL);
responseBean.setStatus(ErrorCode.STATUS_CODE_2000);
responseBean.setMessage(GConstants.OK);
responseBean.setData(uploadFile);
return responseBean;
}
@ApiOperation(value = "15.2 文件上传接口2", httpMethod = "POST", response = ResponseBean.class, notes = "批量文件上传", position = 1)
@ResponseBody
@RequestMapping(value="/multipart", method ={RequestMethod.POST}, produces={MediaType.APPLICATION_JSON_VALUE})
public ResponseBean multipart(HttpServletRequest request, HttpServletResponse response, RequestBean requestBean) {
ResponseBean responseBean = new ResponseBean();
// UploadBean uploadFile = null;
List<UploadFileBean> uploadFiles = null;
String clientip = Util.getOnlineIP(request);
// UploadBean uploadFile = null;
// uploadFile = JSON.parseObject(requestBean.getContent(),
// UploadBean.class);
UploadBean uploadFile = new UploadBean();
// uploadFile.setModule("user/company");
uploadFile.setAppCode(GConstants.DEFAULT_APP_CODE);
uploadFiles = frontUploadService.addMultipartFile(request, uploadFile, clientip);
if (uploadFiles == null || uploadFiles.size() == 0) {
responseBean.setStatus(ErrorCode.STATUS_CODE_4001);
responseBean.setMessage("获取不到文件列表!");
return responseBean;
}
uploadFile.setSize(uploadFiles.size());
uploadFile.setUrl(GConstants.FILE_PREFIX_URL);
responseBean.setStatus(ErrorCode.STATUS_CODE_2000);
responseBean.setMessage(GConstants.OK);
responseBean.setData(uploadFile);
return responseBean;
}
@ApiOperation(value = "批量文件上传", httpMethod = "POST", response = ResponseBean.class, notes = "批量文件上传", position = 1)
@ResponseBody
@RequestMapping(value="/token", method ={RequestMethod.POST}, produces={MediaType.APPLICATION_JSON_VALUE})
public Map<String, Object> token(HttpServletRequest req, HttpServletResponse resp) {
// 创建一个通用的多部分解析器
// final String token = req.getParameter("token");
Map<String, Object> map = new HashMap<String, Object>();
map.put("success", true);
map.put("token", Util.getGenericCode());
return map;
}
@ApiOperation(value = "批量文件上传", httpMethod = "GET", response = ResponseBean.class, notes = "批量文件上传", position = 1)
@ResponseBody
@RequestMapping(value="/doUploadFile", method ={RequestMethod.GET}, produces={MediaType.APPLICATION_JSON_VALUE})
public Map<String, Object> doUploadFile() {
// 创建一个通用的多部分解析器
Map<String, Object> map = new HashMap<String, Object>();
map.put("success", true);
map.put("message", "");
map.put("start", 0);
return map;
}
@ApiOperation(value = "批量文件上传", httpMethod = "POST", response = ResponseBean.class, notes = "批量文件上传", position = 1)
@ResponseBody
@RequestMapping(value="/doUploadFile", method ={RequestMethod.POST}, produces={MediaType.APPLICATION_JSON_VALUE})
public Map<String, Object> doUploadFile(HttpServletRequest request, HttpServletResponse resp) {
// 创建一个通用的多部分解析器
int start = 0;
try {
start = Integer.parseInt(request.getParameter("size"));
String name = request.getParameter("name");
String moduleName = request.getParameter("moduleName");
String appCode = request.getParameter("appCode") == null ? GConstants.DEFAULT_APP_CODE
: request.getParameter("appCode");// 本次文件上传记录CODE
String clientip = Util.getOnlineIP(request);
if (StringUtils.isBlank(moduleName)) {// 如果没有传则默认保存到files下面
moduleName = "files";
} else {
moduleName = moduleName.replaceAll("^/+|/+$|[^0-9|a-z|A-Z|/]+", "");// 替换非法字符串
if (moduleName.length() == 0 || moduleName.length() > 64)// 如果没有传则默认保存到files下面
moduleName = "files";
}
String sessionId = DigestUtils.md5Hex(
Util.getRandom(100, 999) + ":" + System.currentTimeMillis() + ":" + Util.getRandom(100, 999));
UploadFileBean fileBean = null;
fileBean = frontUploadService.addUploadFile(sessionId, request.getInputStream(), "", name, "", moduleName, appCode,
clientip,null);
if (fileBean != null) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("success", true);
map.put("message", "");
map.put("start", start);
map.put("file", fileBean);
return map;
}
} catch (Exception e) {
e.printStackTrace();
}
Map<String, Object> map = new HashMap<String, Object>();
map.put("success", false);
map.put("message", "");
map.put("start", 0);
return map;
}
@ApiOperation(value = "批量文件上传", httpMethod = "GET", response = ResponseBean.class, notes = "批量文件上传", position = 1)
@ResponseBody
@RequestMapping(value="/download", method ={RequestMethod.GET}, produces={MediaType.APPLICATION_JSON_VALUE})
public void download(RequestBean requestBean, HttpServletResponse response, HttpServletRequest request) {
FileBean bean = requestBean.getObjectBean(FileBean.class);
// File baseUploadDir = new File(GConstants.FILE_UPLOAD_DIR, filepath);
InputStream in = null;
OutputStream out = null;
try {
// 设置文件MIME类型
response.setContentType("application/form-data;charset=utf-8");
// String downloadFileName=Encodes.urlEncode(bean.getName());
String downloadFileName = new String(bean.getName().getBytes("gbk"), "ISO8859-1");
String agent = (String) request.getHeader("USER-AGENT");
if (agent != null && agent.toLowerCase().indexOf("firefox") > 0) {
downloadFileName = "=?UTF-8?B?" + (new String(Base64.encodeBase64(bean.getName().getBytes("UTF-8"))))
+ "?=";
} /*
* else{ downloadFileName = URLDecoder.decode(bean.getName(),
* "UTF-8"); }
*/
// 设置Content-Disposition
response.setHeader("Content-Disposition", "attachment; filename=" + downloadFileName);
// 获取目标文件的绝对路径
String fullFileName = GConstants.FILE_UPLOAD_DIR + bean.getPath();
// 读取文件
in = new FileInputStream(fullFileName);
out = response.getOutputStream();
// 写文件
int b;
while ((b = in.read()) != -1) {
out.write(b);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
}
}
}
package com.ejweb.modules.front.upload.bean;
import com.alibaba.fastjson.annotation.JSONField;
/**
* 单个文件实体
* @team IT Team
* @author renmb
* @version 1.0
* @time 2016-03-22
*
*/
public class FileBean {
private String name;
private String extesion;
@JSONField(deserialize=false)
private String path;
private String thumbs;
private String md5;
private int size;
@JSONField(serialize=false)
private String summary;
private int width;// 图片特有
private int height;// 图片特有
private int status=0;// 0:未处理 1:成功 2:格式不运行上传
public String getThumbs() {
return thumbs;
}
public void setThumbs(String thumbs) {
this.thumbs = thumbs;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getExtesion() {
return extesion;
}
public void setExtesion(String extesion) {
this.extesion = extesion;
}
public String getMd5() {
return md5;
}
public void setMd5(String md5) {
this.md5 = md5;
}
}
package com.ejweb.modules.front.upload.bean;
import com.alibaba.fastjson.annotation.JSONField;
import com.ejweb.core.base.BaseBean;
import java.util.List;
/**
* 接口请求Content实体
* @team IT Team
* @author renmb
* @version 1.0
* @time 2016-03-22
*
*/
public class UploadBean extends BaseBean {
// @NotEmpty(message="module字段不能为NULL")
private String module;
private String contentType="png";// 文件类型,即文件的后缀名称,如png,mp3登录
private String sessionId;
private String clientip;
private String url;
private String orientataion;
@JSONField(deserialize=false)
private int size;// 成功处理的文件格式
List<UploadFileBean> files;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public String getSessionId() {
return sessionId;
}
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
public String getModule() {
return module;
}
public void setModule(String module) {
this.module = module;
}
public List<UploadFileBean> getFiles() {
return files;
}
public void setFiles(List<UploadFileBean> files) {
this.files = files;
}
public String getClientip() {
return clientip;
}
public void setClientip(String clientip) {
this.clientip = clientip;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public String getOrientataion() {
return orientataion;
}
public void setOrientataion(String orientataion) {
this.orientataion = orientataion;
}
}
package com.ejweb.modules.front.upload.bean;
import com.alibaba.fastjson.annotation.JSONField;
/**
* 单个文件实体
* @team IT Team
* @author renmb
* @version 1.0
* @time 2016-03-22
*
*/
public class UploadFileBean {
private String name;
private String inputName;
private String extesion;
@JSONField(deserialize=false)
private String path;
private String thumbs;
private String md5;
private int size;
@JSONField(serialize=false)
private String summary;
private int width;// 图片特有
private int height;// 图片特有
private int status=0;// 0:未处理 1:成功 2:格式不允许上传
private String data;// BASE64字符编码
private String orientataion;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getInputName() {
return inputName;
}
public void setInputName(String inputName) {
this.inputName = inputName;
}
public String getExtesion() {
return extesion;
}
public void setExtesion(String extesion) {
this.extesion = extesion;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getThumbs() {
return thumbs;
}
public void setThumbs(String thumbs) {
this.thumbs = thumbs;
}
public String getMd5() {
return md5;
}
public void setMd5(String md5) {
this.md5 = md5;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public String getOrientataion() {
return orientataion;
}
public void setOrientataion(String orientataion) {
this.orientataion = orientataion;
}
}
package com.ejweb.modules.front.upload.dao;
import com.ejweb.core.base.BaseDao;
import com.ejweb.core.base.FindEntity;
import com.ejweb.core.persistence.annotation.MyBatisDao;
import com.ejweb.modules.front.upload.entity.UploadEntity;
/**
* @team IT Team
* @author renmb
* @version 1.0
* @time 2016-03-22
*
*/
@MyBatisDao
public interface FrontUploadDao extends BaseDao {
public Long addUploadFile(UploadEntity fileUploadEntity);
public UploadEntity getUploadEntityByPath(FindEntity entity);
}
package com.ejweb.modules.front.upload.entity;
import com.ejweb.core.base.BaseEntity;
/**
*
* 上传文件返回实体
* @team IT Team
* @author renmb
* @version 1.0
* @time 2016-03-22
*
*/
public class UploadEntity extends BaseEntity {
/**
*
*/
private static final long serialVersionUID = 8395156713205116362L;
private String id;
private String appCode;
private String sessionId;
private String clientip;
private String name;
private String inputName;
private String module;
private String extesion;
private String path;
private String thumbs;
private String md5;
private int size;
private String summary;
private int width;
private int height;
private String orientataion;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSessionId() {
return sessionId;
}
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
public String getClientip() {
return clientip;
}
public void setClientip(String clientip) {
this.clientip = clientip;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public String getAppCode() {
return appCode;
}
public void setAppCode(String appCode) {
this.appCode = appCode;
}
public String getThumbs() {
return thumbs;
}
public void setThumbs(String thumbs) {
this.thumbs = thumbs;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getInputName() {
return inputName;
}
public void setInputName(String inputName) {
this.inputName = inputName;
}
public String getModule() {
return module;
}
public void setModule(String module) {
this.module = module;
}
public String getExtesion() {
return extesion;
}
public void setExtesion(String extesion) {
this.extesion = extesion;
}
public String getMd5() {
return md5;
}
public void setMd5(String md5) {
this.md5 = md5;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public String getOrientataion() {
return orientataion;
}
public void setOrientataion(String orientataion) {
this.orientataion = orientataion;
}
}
package com.ejweb.modules.front.upload.service;
import com.ejweb.conf.GConstants;
import com.ejweb.core.base.BaseService;
import com.ejweb.core.base.FindEntity;
import com.ejweb.core.util.Util;
import com.ejweb.core.utils.IdWorker;
import com.ejweb.core.utils.PathFormatUtils;
import com.ejweb.modules.front.upload.bean.UploadBean;
import com.ejweb.modules.front.upload.bean.UploadFileBean;
import com.ejweb.modules.front.upload.dao.FrontUploadDao;
import com.ejweb.modules.front.upload.entity.UploadEntity;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* 文件上传统一处理Service
*
* @team IT Team
* @author renmb
* @version 1.0
* @time 2016年7月24日
*/
@Service
@Transactional(readOnly=true)
public class FrontUploadService extends BaseService<FrontUploadDao> {
private static Logger LOG = Logger.getLogger(com.ejweb.modules.upload.service.UploadService.class);
private static final String PATH_FORMAt = GConstants.getValue("file.path.format", "{yyyy}{mm}{dd}");
/**
* 使用Spring的CommonsMultipartFile处理文件,每个表单的input名称必须为file
*
* @author renmb
* @time 2016年7月24日
* @param files
* @param moduleName
* @param appCode
* @param clientip
* @return
*/
@Transactional(readOnly = false)
public List<UploadFileBean> addMultipartFile(CommonsMultipartFile[] files,
String moduleName, String appCode, String clientip){
UploadBean uploadFile = new UploadBean();
uploadFile.setModule(moduleName);
uploadFile.setAppCode(appCode);
return this.addMultipartFile(files, uploadFile, clientip);
}
/**
* 使用Spring的CommonsMultipartFile处理文件,每个表单的input名称必须为file
*
* @author renmb
* @time 2016年7月24日
* @param files
* @param uploadFile
* @param clientip
* @return
*/
@Transactional(readOnly = false)
public List<UploadFileBean> addMultipartFile(CommonsMultipartFile[] files, UploadBean uploadFile, String clientip){
if(files == null || files.length == 0){
return null;
}
List<UploadFileBean> uploadFiles = null;
// boolean isVerifyFileName = true;// 是否需要验证文件名称
String message = validate(uploadFile);
if(message == null){
// uploadFile.setSize(0);
// uploadFile.setUrl(GConstants.FILE_PREFIX_URL);
uploadFiles = new ArrayList<UploadFileBean>(6);
uploadFile.setFiles(uploadFiles);
// uploadFiles = uploadFile.getFiles();
// if(uploadFiles == null){// 如果没有传文件列表则新建一个列表
// uploadFiles = new ArrayList<UploadFileBean>(6);
// uploadFile.setFiles(uploadFiles);
//// isVerifyFileName = false;
// }
// String moduleName = uploadFile.getModule();// 模块名称
// if(StringUtils.isBlank(moduleName)){// 如果没有传则默认保存到files下面
// moduleName = "files";
// } else{
// moduleName = moduleName.replaceAll("^/+|/+$|[^0-9|a-z|A-Z|/]+", "");// 替换非法字符串
// if(moduleName.length() == 0 || moduleName.length()>64)// 如果没有传则默认保存到files下面
// moduleName = "files";
// }
// uploadFile.setModule(moduleName);
// 生成本次会话的随机数随机数
String sessionId = DigestUtils.md5Hex(Util.getRandom(100, 999)+":"
+System.currentTimeMillis()+":"+ Util.getRandom(100, 999));
// uploadFile.setSessionId(sessionId);
for (CommonsMultipartFile file:files) {// 遍历所有提交的文件
try {
String originalFilename = file.getOriginalFilename();
if(StringUtils.isNotBlank(originalFilename)){// 文件扩展名称不能为NULL
InputStream in = file.getInputStream();
String contentType = uploadFile.getContentType();
UploadFileBean fileBean = this.addUploadFile(sessionId, in, file.getName(), originalFilename, contentType,
uploadFile.getModule(), uploadFile.getAppCode(), clientip,uploadFile.getOrientataion());
if(uploadFile.getOrientataion()!=null){
// if("6".equals(uploadFile.getOrientataion())){
// BufferedImage src = ImageIO.read(new File(GConstants.FILE_UPLOAD_DIR+fileBean.getPath()));
// BufferedImage des = RotateImage.Rotate(src,90);
// System.out.print("n\n\n\n\n\n\n\n\n\n"+uploadFile.getOrientataion()+"n\n\n\n\n\n\n\n\n\n"+GConstants.FILE_UPLOAD_DIR+fileBean.getPath()+"n\n\n\n\n\n\n\n\n\n");
// ImageIO.write(des, fileBean.getExtesion(), new File(GConstants.FILE_UPLOAD_DIR+fileBean.getPath()));
// }
// if("8".equals(uploadFile.getOrientataion())){
// BufferedImage src = ImageIO.read(new File(GConstants.FILE_UPLOAD_DIR+fileBean.getPath()));
// BufferedImage des = RotateImage.Rotate(src,270);
// System.out.print("n\n\n\n\n\n\n\n\n\n"+uploadFile.getOrientataion()+"n\n\n\n\n\n\n\n\n\n"+GConstants.FILE_UPLOAD_DIR+fileBean.getPath()+"n\n\n\n\n\n\n\n\n\n");
// ImageIO.write(des, fileBean.getExtesion(), new File(GConstants.FILE_UPLOAD_DIR+fileBean.getPath()));
// }
// if("3".equals(uploadFile.getOrientataion())){
// BufferedImage src = ImageIO.read(new File(GConstants.FILE_UPLOAD_DIR+fileBean.getPath()));
// BufferedImage des = RotateImage.Rotate(src,180);
// System.out.print("n\n\n\n\n\n\n\n\n\n"+uploadFile.getOrientataion()+"n\n\n\n\n\n\n\n\n\n"+GConstants.FILE_UPLOAD_DIR+fileBean.getPath()+"n\n\n\n\n\n\n\n\n\n");
// ImageIO.write(des, fileBean.getExtesion(), new File(GConstants.FILE_UPLOAD_DIR+fileBean.getPath()));
// }
}
fileBean.setOrientataion(uploadFile.getOrientataion());
uploadFiles.add(fileBean);
}
} catch (Exception e) {
// TODO: handle exception
}
// if(file !=null){
// // 统一文件处理
// addUploadFile(uploadFiles, uploadFile, isVerifyFileName,
// sessionId, file, clientip);
// }
}
return uploadFiles;
}
return uploadFiles;
}
/**
* 使用Spring的CommonsMultipartFile处理文件,每个表单的input名称必须为file
*
* @author renmb
* @time 2016年7月24日
* @param request
* @param moduleName
* @param appCode
* @param clientip
* @return
*/
@Transactional(readOnly = false)
public List<UploadFileBean> addMultipartFile(HttpServletRequest request,
String moduleName, String appCode, String clientip){
UploadBean uploadFile = new UploadBean();
uploadFile.setModule(moduleName);
uploadFile.setAppCode(appCode);
return this.addMultipartFile(request, uploadFile, clientip);
}
/**
* 使用Spring的CommonsMultipartResolver处理文件,每个input的名称都不一致
*
* @author renmb
* @time 2016年7月24日
* @param request
* @param uploadFile
* @param clientip
* @return
*/
@Transactional(readOnly = false)
public List<UploadFileBean> addMultipartFile(HttpServletRequest request,
UploadBean uploadFile, String clientip){
try {
List<UploadFileBean> uploadFiles = null;
// boolean isVerifyFileName = true;// 是否需要验证文件名称
String message = validate(uploadFile);
if(message == null){
// uploadFile.setSize(0);
// 创建一个通用的多部分解析器
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
request.getSession().getServletContext());
// 判断 request 是否有文件上传,即多部分请求
if (multipartResolver != null && multipartResolver.isMultipart(request)) {
// uploadFile.setUrl(GConstants.FILE_PREFIX_URL);
uploadFiles = new ArrayList<UploadFileBean>(6);
uploadFile.setFiles(uploadFiles);
// if(uploadFiles == null){// 如果没有传文件列表则新建一个列表
// uploadFiles = new ArrayList<UploadFileBean>(6);
// uploadFile.setFiles(uploadFiles);
// isVerifyFileName = false;
// }
String moduleName = uploadFile.getModule();// 模块名称
// if(StringUtils.isBlank(moduleName)){// 如果没有传则默认保存到files下面
// moduleName = "files";
// } else{
// moduleName = moduleName.replaceAll("^/+|/+$|[^0-9|a-z|A-Z|/]+", "");// 替换非法字符串
// if(moduleName.length() == 0 || moduleName.length()>64)// 如果没有传则默认保存到files下面
// moduleName = "files";
// }
// uploadFile.setModule(moduleName);
// 生成本次会话的随机数随机数
String sessionId = DigestUtils.md5Hex(Util.getRandom(100, 999)+":"
+System.currentTimeMillis()+":"+ Util.getRandom(100, 999));
// uploadFile.setSessionId(sessionId);
// 转换成多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
// 取得request中的所有文件名
Iterator<String> iter = multiRequest.getFileNames();
while (iter.hasNext()) {
try {
MultipartFile file = multiRequest.getFile(iter.next());
if (file != null) {// 取得上传文件
String originalFilename = file.getOriginalFilename();
if(StringUtils.isNotBlank(originalFilename)){// 文件扩展名称不能为NULL
InputStream in = file.getInputStream();
String contentType = uploadFile.getContentType();
UploadFileBean fileBean = this.addUploadFile(sessionId, in, file.getName(), originalFilename, contentType,
moduleName, uploadFile.getAppCode(), clientip,uploadFile.getOrientataion());
fileBean.setOrientataion(uploadFile.getOrientataion());
uploadFiles.add(fileBean);
}
}
} catch (Exception e) {
// TODO: handle exception
}
// 取得上传文件
// MultipartFile file = multiRequest.getFile(iter.next());
// file.getName();
// if (file != null) {
// // 统一文件处理
// addUploadFile(uploadFiles, uploadFile, isVerifyFileName,
// sessionId, file, clientip);
// }
}
}
return uploadFiles;
}
} catch (Exception e) {
// TODO: handle exception
}
return null;
}
/**
* 通过文件流上传文件
*
* @param sessionId
* @param in
* @param inputName
* @param originalFilename
* @param contentType
* @param moduleName
* @param appCode
* @param clientip
* @return
*/
@SuppressWarnings("resource")
@Transactional(readOnly = false)
public UploadFileBean addUploadFile(String sessionId, InputStream in, String inputName, String originalFilename,
String contentType, String moduleName, String appCode, String clientip,String orientataion) {
OutputStream os = null;
ByteArrayOutputStream baos = null;
UploadEntity fileUploadEntity=null;
// InputStream in = null;
try {
// String originalFilename = file.getOriginalFilename();
if(StringUtils.isBlank(originalFilename)){// 文件扩展名称不能为NULL
LOG.debug("无法获取文件名称:"+originalFilename);
return null;
}
if("blob".equals(originalFilename)){// 上传的二进制文件,兼容H5文件无法上传的情况
if(StringUtils.isEmpty(contentType)){// 默认为MP3格式
originalFilename = "blob.mp3";
} else {
originalFilename = "blob."+contentType;
}
}
String extesionName = Util.getExtensionName(originalFilename);
if(extesionName == null || extesionName.length() == 0){// 文件扩展名称不能为NULL
LOG.debug("无法获取文件扩展名:"+originalFilename);
}
UploadFileBean fileBean = null;
// uploadFile.setSize(uploadFile.getSize()+1);
if(extesionName == null ||
GConstants.FILE_FILTERS.get(extesionName.toLowerCase()) == null){// 不允许上传的文件
LOG.debug("此类型文件不允许上传:"+originalFilename);
fileBean = new UploadFileBean();
fileBean.setInputName("");
fileBean.setPath(null);
fileBean.setName(originalFilename);
fileBean.setExtesion(extesionName);
fileBean.setStatus(2);
return fileBean;
}
// 拿到上传文件的输入流
// in = request.getInputStream();
in = new BufferedInputStream(in);
baos = new ByteArrayOutputStream();
byte[] buf = new byte[GConstants.BUFFER_SIZE];
// 以写字节的方式写文件
int size = in.read(buf);
while (size != -1) {
baos.write(buf, 0, size);
size = in.read(buf);
}
byte[] data = baos.toByteArray();
// byte[] data = IOUtils.toByteArray(in);
// 待扩展名称的MOD5
String md5 = DigestUtils.md5Hex(data)+extesionName;
fileBean = new UploadFileBean();
fileBean.setName(originalFilename);
if(StringUtils.isBlank(inputName)){
fileBean.setInputName("");
} else {
fileBean.setInputName(inputName);
}
fileBean.setSize(data.length);
fileBean.setMd5(md5);
fileBean.setExtesion(extesionName);
if(StringUtils.isBlank(moduleName)){// 如果没有传则默认保存到files下面
moduleName = "files";
} else{
moduleName = moduleName.replaceAll("^/+|/+$|[^0-9|a-z|A-Z|/]+", "");// 替换非法字符串
moduleName = moduleName.replaceAll("[\\|//]+", "/");
if(moduleName.length() == 0 || moduleName.length()>64)// 如果没有传则默认保存到files下面
moduleName = "files";
}
// 文件保存路径:基本路径+模块名称+日期
String baseDatePath = PathFormatUtils.parse(PATH_FORMAt);//FORMAT.format(System.currentTimeMillis());
String basePath = moduleName+ GConstants.FS+extesionName.replaceAll("\\.", "")+ GConstants.FS;
// 上传文件基本地址
File baseUploadDir = new File(GConstants.FILE_UPLOAD_DIR, baseDatePath+ GConstants.FS+ GConstants.FILE_IMAGE_ACTUALS+ GConstants.FS+basePath);
if(!baseUploadDir.exists()){// 如果文件夹不存在则创建
baseUploadDir.mkdirs();
}
// String prefixFilename = "";
// if(StringUtils.isBlank(GConstants.getValue("file.prefix.filename.format")) == false){
// try {
// SimpleDateFormat PRE_FORMAT = new SimpleDateFormat(GConstants.getValue("file.prefix.filename.format"));
// prefixFilename = PRE_FORMAT.format(System.currentTimeMillis());// 文件名称前面部分
// } catch (Exception e) {
// // TODO: handle exception
// }
// }
// String sessionId = DigestUtils.md5Hex(Util.getRandom(100, 999)+":"
// +System.currentTimeMillis()+":"+Util.getRandom(100, 999));
// 文件保存地址
File uploadFilePath = new File(baseUploadDir, md5);
LOG.info("原文件服务器绝对路径:"+uploadFilePath);
// 将数据保存到指定文件
os = new FileOutputStream(uploadFilePath);
os = new BufferedOutputStream(os);
os.write(data);
os.flush();
os.close();
this.copyToMultiplePaths(uploadFilePath);
// 设置文件相关信息
fileUploadEntity = new UploadEntity();
// 如果上传文件为图片则获取图片的宽度高度
if(GConstants.FILE_FILTERS.get(extesionName) != null &&
GConstants.FILE_FILTERS.get(extesionName)){
BufferedImage image = this.getBufferedImage(data);
if(image != null){// 生成图片缩略图
fileBean.setWidth(image.getWidth());
fileBean.setHeight(image.getHeight());
if(GConstants.FILE_ALLOW_THUMBS){// 图片压缩保存
int with = GConstants.getIntValue("file.image.thumb.width", 640);
int height = GConstants.getIntValue("file.image.thumb.height", 640);
if(image.getWidth()>with || image.getHeight()>height){
File baseUploadThumbsDir = new File(GConstants.FILE_UPLOAD_DIR,
baseDatePath+ GConstants.FS+ GConstants.FILE_IMAGE_THUMBS+ GConstants.FS+basePath);
if(!baseUploadThumbsDir.exists()){// 如果文件夹不存在则创建
baseUploadThumbsDir.mkdirs();
}
File uploadThumbsFilePath = new File(baseUploadThumbsDir, md5);
LOG.info("缩略图文件服务器绝对路径:"+uploadThumbsFilePath);
Thumbnails.of(image).size(with, height)
.keepAspectRatio(true).outputQuality(1f)
.toFile(uploadThumbsFilePath);
// 设置缩略图地址前缀
fileBean.setThumbs(baseDatePath+ GConstants.FS+ GConstants.FILE_IMAGE_THUMBS+ GConstants.FS+basePath+md5);
fileUploadEntity.setThumbs(baseDatePath+ GConstants.FS+ GConstants.FILE_IMAGE_THUMBS+ GConstants.FS+basePath+md5);
this.copyToMultiplePaths(uploadThumbsFilePath);
} else{
fileBean.setThumbs(baseDatePath+ GConstants.FS+ GConstants.FILE_IMAGE_ACTUALS+ GConstants.FS+basePath+md5);
fileUploadEntity.setThumbs(fileBean.getThumbs());
}
}
}
}
fileUploadEntity.setName(fileBean.getName());
fileUploadEntity.setModule(moduleName);
fileUploadEntity.setMd5(md5);
fileUploadEntity.setExtesion(extesionName);
fileUploadEntity.setPath(baseDatePath+ GConstants.FS+ GConstants.FILE_IMAGE_ACTUALS+ GConstants.FS+basePath+md5);
fileUploadEntity.setAppCode(appCode);
fileUploadEntity.setWidth(fileBean.getWidth());
fileUploadEntity.setHeight(fileBean.getHeight());
fileUploadEntity.setSize(data.length);
fileUploadEntity.setClientip(clientip);
fileUploadEntity.setOrientataion(orientataion);
fileUploadEntity.setSessionId(sessionId);
fileUploadEntity.setInputName(fileBean.getInputName());
fileUploadEntity.setId(IdWorker.getNextId());
// 保存文件到数据库
dao.addUploadFile(fileUploadEntity);
fileBean.setExtesion(extesionName);
fileBean.setSize(data.length);
fileBean.setMd5(md5);
fileBean.setPath(baseDatePath+ GConstants.FS+ GConstants.FILE_IMAGE_ACTUALS+ GConstants.FS+basePath+md5);
fileBean.setStatus(1);
return fileBean;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
IOUtils.closeQuietly(os);
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(baos);
}
return null;
}
/**
* 获取图片文件
*
* @author renmb
* @time 2016年7月24日
* @param data
* @return
*/
public BufferedImage getBufferedImage(byte[] data){
BufferedImage image = null;
try {
image = ImageIO.read(new ByteArrayInputStream(data));
return image;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 将文件复制到其它备份磁盘
*
* author renmb
* @time 2017年05月18日
* @param file
*/
private void copyToMultiplePaths (final File file){
final String dirs = GConstants.getValue("file.upload.dirs");
if(StringUtils.isNotEmpty(dirs)){
try {
Thread thread = new Thread(new Runnable(){
@Override
public void run() {
String basePath = file.getAbsolutePath().replace(GConstants.FILE_UPLOAD_DIR, "");
String[] paths = dirs.split(";");
for (String path:paths){
InputStream input = null;
OutputStream output = null;
try{
File newFilePath = new File(path, basePath);
if(!newFilePath.getParentFile().exists()){// 如果文件夹不存在则创建
newFilePath.getParentFile().mkdirs();
}
LOG.debug("UploadService copyToMultiplePaths: "+file.getAbsolutePath()+" TO "+newFilePath.getAbsolutePath());
input = new FileInputStream(file);
output = new FileOutputStream(newFilePath);
IOUtils.copy(input, output);
} catch (Exception e){
IOUtils.closeQuietly(input);
IOUtils.closeQuietly(output);
}
}
}
});
thread.start();
} catch (Exception e){
LOG.error(e.getMessage());
}
}
}
public UploadEntity getUploadEntityByPath(String code){
FindEntity entity = new FindEntity(code);
return dao.getUploadEntityByPath(entity);
}
}
/**
*
*/
package com.ejweb.modules.front.upload.util;
import com.ejweb.conf.GConstants;
import com.ejweb.modules.upload.bean.UploadFileBean;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import java.io.*;
import java.util.List;
/**
*
* @team IT Team
* @author renmb
* @version 1.0
* @time 2016年8月8日
*/
public class UploadUtils {
/**
* 更加表单名称获取上传的文件实体
*
* @author renmb
* @time 2016年8月8日
* @param uploadFiles 上传的文件列表
* @param inputName
* @return
*/
public UploadFileBean getUploadFileByInputName(List<UploadFileBean> uploadFiles, String inputName){
if(StringUtils.isBlank(inputName) || uploadFiles == null || uploadFiles.size() == 0)
return null;
for(int i=0,len=uploadFiles.size();i<len;i++){// 以文件名称匹配
// 获取同MD5或者同名的文件对象
if(uploadFiles.get(i) != null && inputName.equalsIgnoreCase(uploadFiles.get(i).getInputName())){
return uploadFiles.get(i);
}
}
return null;
}
/**
* 获取上传文件的文件路径
*
* @author renmb
* @time 2016年8月8日
* @param uploadFiles
* @param inputName
* @return
*/
public String getUploadFilePathByInputName(List<UploadFileBean> uploadFiles, String inputName){
if(StringUtils.isBlank(inputName) || uploadFiles == null || uploadFiles.size() == 0)
return null;
for(int i=0,len=uploadFiles.size();i<len;i++){// 以文件名称匹配
// 获取同MD5或者同名的文件对象
if(uploadFiles.get(i) != null && inputName.equalsIgnoreCase(uploadFiles.get(i).getInputName())){
return uploadFiles.get(i).getPath();
}
}
return null;
}
/**
* 将文件复制到其它备份磁盘
*
* author renmb
* @time 2017年05月18日
* @param file
*/
public static void copyToMultiplePaths (final File file){
final String dirs = GConstants.getValue("file.upload.dirs");
if(StringUtils.isNotEmpty(dirs)){
try {
Thread thread = new Thread(new Runnable(){
@Override
public void run() {
String basePath = file.getAbsolutePath().replace(GConstants.FILE_UPLOAD_DIR, "");
String[] paths = dirs.split(";");
for (String path:paths){
InputStream input = null;
OutputStream output = null;
try{
File newFilePath = new File(path, basePath);
if(!newFilePath.getParentFile().exists()){// 如果文件夹不存在则创建
newFilePath.getParentFile().mkdirs();
}
// LOG.debug("UploadService copyToMultiplePaths: "+file.getAbsolutePath()+" TO "+newFilePath.getAbsolutePath());
input = new FileInputStream(file);
output = new FileOutputStream(newFilePath);
IOUtils.copy(input, output);
} catch (Exception e){
IOUtils.closeQuietly(input);
IOUtils.closeQuietly(output);
}
}
}
});
thread.start();
} catch (Exception e){
e.printStackTrace();
}
}
}
}
package com.ejweb.modules.front.upload.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* 页面上传路径
* @team IT Team
* @author renmb
* @version 1.0
* @time 2016-03-22
*
*/
@Controller
@RequestMapping(value="/front/web/upload")
public class FrontUploadAction {
@RequestMapping("/index")
public String index(){
return "modules/upload/index";
}
@RequestMapping("/multipart")
public String multipart(){
return "modules/upload/multipart";
}
@RequestMapping("/stream/upload")
public String streamUpload(){
return "modules/upload/stream";
}
}
...@@ -96,6 +96,9 @@ file.image.thumb.height=640 ...@@ -96,6 +96,9 @@ file.image.thumb.height=640
# The Prefix Url # The Prefix Url
file.prefix.url=http://127.0.0.1:8080/static/ file.prefix.url=http://127.0.0.1:8080/static/
# The Prefix separator
file.upload.path.separator = /
# The Push Server Config # The Push Server Config
push.server.url=http://123.56.146.81:1880/v1/ push.server.url=http://123.56.146.81:1880/v1/
......
<?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.ejweb.modules.front.upload.dao.FrontUploadDao">
<sql id="fileColumns">
id,
app_code,
session_id,
clientip,
module,
md5,
name,
input_name,
path,
thumbs,
extesion,
summary,
size,
width,
orientataion,
height
</sql>
<insert id="addUploadFile" useGeneratedKeys="true" keyProperty="id">
INSERT INTO upload_files(
<include refid="fileColumns"/>
) VALUES(
#{id},
#{appCode},
#{sessionId},
#{clientip},
#{module},
#{md5},
#{name},
#{inputName},
#{path},
#{thumbs},
#{extesion},
#{summary},
#{size},
#{width},
#{orientataion},
#{height}
)
</insert>
<select id="getUploadEntityByPath" resultType="com.ejweb.modules.upload.entity.UploadEntity">
SELECT
<include refid="fileColumns"/>
FROM upload_files
WHERE path = #{code}
ORDER BY created DESC
limit 1
</select>
</mapper>
\ No newline at end of file
<?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.ejweb.modules.front.report.dao.FrontReportDao">
<sql id="reportColumns">
id,
report_project,
report_city,
report_time,
report_content,
report_person_name,
report_person_tel,
report_person_email,
report_source,
report_status,
supplement_company,
supplement_department,
supplement_informant,
supplement_title,
supplement_type,
supplement_area,
supplement_project,
supplement_content,
deal_person_name,
deal_result,
exchange_before_user,
exchange_after_user,
create_by,
create_date,
update_by,
update_date
</sql>
<insert id="insertReport" useGeneratedKeys="true" keyProperty="id">
INSERT INTO report(
id,
report_project,
report_city,
report_time,
report_content,
report_person_name,
report_person_tel,
report_person_email,
report_source,
report_status,
exchange_before_user,
exchange_after_user,
create_by,
create_date,
update_by,
update_date
) VALUES(
#{id},
#{reportProject},
#{reportCity},
#{reportTime},
#{reportContent},
#{reportPersonName},
#{reportPersonTel},
#{reportPersonEmail},
#{reportSource},
#{reportStatus},
#{exchangeBeforeUser},
#{exchangeAfterUser},
#{createBy},
#{createDate},
#{updateBy},
#{updateDate}
)
</insert>
<insert id="insertReportAttachment">
INSERT INTO report_attachment(
id,
report_id,
attachment_name,
attachment_path,
attachment_size,
attachment_type
)VALUES(
#{id},
#{reportId},
#{attachmentName},
#{attachmentPath},
#{attachmentSize},
#{attachmentType}
)
</insert>
</mapper>
\ No newline at end of file
...@@ -147,6 +147,18 @@ ...@@ -147,6 +147,18 @@
<servlet-name>ValidateCodeServlet</servlet-name> <servlet-name>ValidateCodeServlet</servlet-name>
<url-pattern>/servlet/validateCodeServlet</url-pattern> <url-pattern>/servlet/validateCodeServlet</url-pattern>
</servlet-mapping> </servlet-mapping>
<!--验证码-->
<servlet>
<servlet-name>captcha</servlet-name>
<servlet-class>com.ejweb.modules.front.report.servlet.CaptchaServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>captcha</servlet-name>
<url-pattern>/front/report/captcha</url-pattern>
</servlet-mapping>
<error-page> <error-page>
<error-code>500</error-code> <error-code>500</error-code>
<location>/WEB-INF/views/error/500.jsp</location> <location>/WEB-INF/views/error/500.jsp</location>
......
...@@ -3,9 +3,9 @@ db.table.prefix=sunac_ ...@@ -3,9 +3,9 @@ db.table.prefix=sunac_
jdbc.type=mysql jdbc.type=mysql
jdbc.driver.class=com.mysql.jdbc.Driver jdbc.driver.class=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/report_sunac?useUnicode=true&characterEncoding=utf-8 jdbc.url=jdbc:mysql://123.56.146.7:3306/sunac_report?useUnicode=true&characterEncoding=utf-8
jdbc.username=root jdbc.username=reportuser
jdbc.password=admin jdbc.password=$R@20$7
#初始化连接 #初始化连接
jdbc.initialSize=0 jdbc.initialSize=0
......
...@@ -147,6 +147,18 @@ ...@@ -147,6 +147,18 @@
<servlet-name>ValidateCodeServlet</servlet-name> <servlet-name>ValidateCodeServlet</servlet-name>
<url-pattern>/servlet/validateCodeServlet</url-pattern> <url-pattern>/servlet/validateCodeServlet</url-pattern>
</servlet-mapping> </servlet-mapping>
<!--验证码-->
<servlet>
<servlet-name>captcha</servlet-name>
<servlet-class>com.ejweb.modules.front.report.servlet.CaptchaServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>captcha</servlet-name>
<url-pattern>/front/report/captcha</url-pattern>
</servlet-mapping>
<error-page> <error-page>
<error-code>500</error-code> <error-code>500</error-code>
<location>/WEB-INF/views/error/500.jsp</location> <location>/WEB-INF/views/error/500.jsp</location>
......
...@@ -96,6 +96,9 @@ file.image.thumb.height=640 ...@@ -96,6 +96,9 @@ file.image.thumb.height=640
# The Prefix Url # The Prefix Url
file.prefix.url=http://127.0.0.1:8080/static/ file.prefix.url=http://127.0.0.1:8080/static/
# The Prefix separator
file.upload.path.separator = /
# The Push Server Config # The Push Server Config
push.server.url=http://123.56.146.81:1880/v1/ push.server.url=http://123.56.146.81:1880/v1/
......
...@@ -3,9 +3,9 @@ db.table.prefix=sunac_ ...@@ -3,9 +3,9 @@ db.table.prefix=sunac_
jdbc.type=mysql jdbc.type=mysql
jdbc.driver.class=com.mysql.jdbc.Driver jdbc.driver.class=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/report_sunac?useUnicode=true&characterEncoding=utf-8 jdbc.url=jdbc:mysql://123.56.146.7:3306/sunac_report?useUnicode=true&characterEncoding=utf-8
jdbc.username=root jdbc.username=reportuser
jdbc.password=admin jdbc.password=$R@20$7
#初始化连接 #初始化连接
jdbc.initialSize=0 jdbc.initialSize=0
......
...@@ -147,6 +147,18 @@ ...@@ -147,6 +147,18 @@
<servlet-name>ValidateCodeServlet</servlet-name> <servlet-name>ValidateCodeServlet</servlet-name>
<url-pattern>/servlet/validateCodeServlet</url-pattern> <url-pattern>/servlet/validateCodeServlet</url-pattern>
</servlet-mapping> </servlet-mapping>
<!--验证码-->
<servlet>
<servlet-name>captcha</servlet-name>
<servlet-class>com.ejweb.modules.front.report.servlet.CaptchaServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>captcha</servlet-name>
<url-pattern>/front/report/captcha</url-pattern>
</servlet-mapping>
<error-page> <error-page>
<error-code>500</error-code> <error-code>500</error-code>
<location>/WEB-INF/views/error/500.jsp</location> <location>/WEB-INF/views/error/500.jsp</location>
......
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