package com.tj720.mip.controller.admin;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.log4j.chainsaw.Main;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import com.itextpdf.text.log.SysoCounter;
import com.sun.mail.handlers.image_gif;
import com.tj720.mip.framework.auth.AuthPassport;
import com.tj720.mip.framework.base.BaseController;
import com.tj720.mip.model.Picture;
import com.tj720.mip.model.User;
import com.tj720.mip.service.table.PictureService;
import com.tj720.mip.springbeans.Config;
import com.tj720.mip.utils.Const;
import com.tj720.mip.utils.DateFormartUtil;
import com.tj720.mip.utils.ImageHepler;
import com.tj720.mip.utils.MyString;
import com.tj720.mip.utils.Tools;
@Controller
public class FileController extends BaseController<User> {
@Autowired
private Config config;
@Autowired
private PictureService pictureService;
@RequestMapping(value = "/file/upload.do")
@ResponseBody
public String upload(@RequestParam(value = "file", required = false) CommonsMultipartFile file,
@RequestParam(defaultValue = "") String callBack, String property, HttpServletRequest request) {
String result = "";
String realFileName = file.getOriginalFilename();
String destDir = Tools.getServicePath(request);
String saveUrl = "";
String suffix = realFileName.substring(realFileName.lastIndexOf(".") + 1).toLowerCase();
JSONObject obj = new JSONObject();
/**
* 文件大小拦截,不能超过20M
*/
if (file.getSize() > 1024 * 1024 * config.getFileSize()) {
obj.put("error", 1);
result = "[ERROR]文件超过最大限制,请上传小于" + config.getFileSize() + "M的文件";
} else if (config.getImageType().indexOf(suffix) < 0 && config.getFileType().indexOf(suffix) < 0) {
// 检查扩展名
obj.put("error", 1);
result = "[ERROR]上传文件格式不对";
} else {
// 检查扩展名
if (config.getImageType().indexOf(suffix) >= 0) {
saveUrl += "back/upload/images";
} else {
saveUrl += "resources/upload/files";
}
saveUrl += "/" + DateFormartUtil.getDateByFormat(DateFormartUtil.YYYY_MM_DD) + "/";
String version = ".MIP." + Tools.getChar(6) + ".1";
// 如果文件包含版本号:.CAV.文件标识.版本号 //版本号CrapApi Version
try {
if (realFileName.contains(".MIP.")) {
String str[] = realFileName.split("\.");
version = ".MIP." + str[str.length - 3] + "." + (Long.parseLong(str[str.length - 2]) + 1);
}
} catch (Exception e) {
e.printStackTrace();
}
realFileName = DateFormartUtil.getDateByFormat(DateFormartUtil.HHmmss) + Tools.getChar(6) + version + "."
+ suffix;
// 保存
try {
if (!new File(destDir + saveUrl).exists()) {
new File(destDir + saveUrl).mkdirs();
}
File targetFile = new File(destDir + saveUrl, realFileName);
file.transferTo(targetFile);
result = saveUrl + realFileName;
obj.put("error", 0);
obj.put("state", "SUCCESS");
obj.put("url", saveUrl + realFileName);
} catch (Exception e) {
obj.put("error", 1);
e.printStackTrace();
result = "[ERROR]上传失败";
}
}
if (!callBack.equals("")) {
if (result.indexOf("[ERROR]") < 0) {
printMsg("<script>parent." + callBack + "('[OK]上传成功','" + result + "','" + property + "')</script>");
} else {
printMsg("<script>parent.uploadImgCallBack('[ERROR]上传失败','" + result + "')</script>");
}
} else {
obj.put("message", result);
// printMsg(obj.toString());
}
return obj.toString();
}
@RequestMapping(value = "/file/uploadPicture.do")
@ResponseBody
public String uploadPicture(@RequestParam(value = "file", required = false) CommonsMultipartFile file,
String objectId, String typeId, @RequestParam(defaultValue = "") String callBack, String property,
HttpServletRequest request) {
String result = "";
String realFileName = file.getOriginalFilename();
// String destDir = Tools.getServicePath(request);
String destDir = config.getRootPath();
String saveUrl = "";
String suffix = realFileName.substring(realFileName.lastIndexOf(".") + 1).toUpperCase();
JSONObject obj = new JSONObject();
/**
* 文件大小拦截,不能超过20M
*/
if (file.getSize() > 20 * 1024 * 1024 * config.getFileSize()) {
obj.put("error", 1);
result = "[ERROR]文件超过最大限制,请上传小于" + (20 * config.getFileSize()) + "M的文件";
} else if (config.getImageType().indexOf(suffix) < 0 && config.getFileType().indexOf(suffix) < 0) {
// 检查扩展名
obj.put("error", 1);
result = "[ERROR]上传文件格式不对";
} else {
// 检查扩展名
if (config.getImageType().indexOf(suffix) >= 0) {
saveUrl += "back/picture";
} else {
saveUrl += "back/picture";
}
String targetFileName = UUID.randomUUID().toString().replace("-", "") + "." + suffix;
// 保存图片
try {
if (!new File(destDir + saveUrl).exists()) {
new File(destDir + saveUrl).mkdirs();
}
File targetFile = new File(destDir + saveUrl, targetFileName);
file.transferTo(targetFile);
Picture picture = new Picture();
// 存数据库
picture.setObjectId(objectId);
picture.setTypeId(typeId);
picture.setName(realFileName);
picture.setUrl(saveUrl + "/" + targetFileName);
picture.setType((byte) 1);
picture.setStatus((byte) 1);
picture.setIsMain((byte) 1);
// 获取原图真实长宽
BufferedImage sourceImg = ImageIO.read(new FileInputStream(targetFile));
picture.setPicWidth(sourceImg.getWidth());
picture.setPicHeight(sourceImg.getHeight());
Picture savePic = pictureService.save(picture);
String picId = savePic.getId();
String picName = savePic.getName();
result = config.getRootUrl() + saveUrl + "/" + targetFileName;
obj.put("error", 0);
obj.put("state", "SUCCESS");
obj.put("url", result);
obj.put("picId", picId);
obj.put("picName", picName);
} catch (Exception e) {
obj.put("error", 1);
e.printStackTrace();
result = "[ERROR]上传失败";
}
}
if (!callBack.equals("")) {
if (result.indexOf("[ERROR]") < 0) {
// printMsg("<script>parent." + callBack + "('[OK]上传成功','" + result + "','" + property + "')</script>");
} else {
// printMsg("<script>parent.uploadImgCallBack('[ERROR]上传失败','" + result + "')</script>");
}
} else {
obj.put("message", result);
// printMsg(obj.toString());
}
return obj.toString();
}
// 上传音频
@RequestMapping(value = "/file/uploadAudio.do")
@ResponseBody
public String uploadAudio(@RequestParam(value = "file", required = false) CommonsMultipartFile file,
String objectId, String typeId, @RequestParam(defaultValue = "") String callBack, String property,
HttpServletRequest request) {
String result = "";
String realFileName = file.getOriginalFilename();
// String destDir = Tools.getServicePath(request);
String destDir = config.getRootPath();
String saveUrl = "";
String suffix = realFileName.substring(realFileName.lastIndexOf(".") + 1).toUpperCase();
JSONObject obj = new JSONObject();
/**
* 文件大小拦截,不能超过50M
*/
if (file.getSize() > 2.5 * 1024 * 1024 * config.getFileSize()) {
obj.put("error", 1);
result = "[ERROR]文件超过最大限制,请上传小于" + (50 * config.getFileSize()) + "M的文件";
} else if (config.getImageType().indexOf(suffix) < 0 && config.getFileType().indexOf(suffix) < 0) {
// 检查扩展名
obj.put("error", 1);
result = "[ERROR]上传文件格式不对";
} else {
// 检查扩展名
if (config.getImageType().indexOf(suffix) >= 0) {
saveUrl += "back/audio";
} else {
saveUrl += "back/audio";
}
String targetFileName = UUID.randomUUID().toString().replace("-", "") + "." + suffix;
// 保存图片
try {
if (!new File(destDir + saveUrl).exists()) {
new File(destDir + saveUrl).mkdirs();
}
File targetFile = new File(destDir + saveUrl, targetFileName);
file.transferTo(targetFile);
result = saveUrl + "/" + targetFileName;
obj.put("error", 0);
obj.put("state", "SUCCESS");
obj.put("url", result);
obj.put("src", config.getRootUrl() + result);
} catch (Exception e) {
obj.put("error", 1);
e.printStackTrace();
result = "[ERROR]上传失败";
}
}
if (!callBack.equals("")) {
if (result.indexOf("[ERROR]") < 0) {
// printMsg("<script>parent." + callBack + "('[OK]上传成功','" + result + "','" + property + "')</script>");
} else {
// printMsg("<script>parent.uploadImgCallBack('[ERROR]上传失败','" + result + "')</script>");
}
} else {
obj.put("message", result);
// printMsg(obj.toString());
}
return obj.toString();
}
// 上传视频
@RequestMapping(value = "/file/uploadVideo.do")
@ResponseBody
public String uploadVideo(@RequestParam(value = "file", required = false) CommonsMultipartFile file,
String objectId, String typeId, @RequestParam(defaultValue = "") String callBack, String property,
HttpServletRequest request) {
String result = "";
String realFileName = file.getOriginalFilename();
// String destDir = Tools.getServicePath(request);
String destDir = config.getRootPath();
String saveUrl = "";
String suffix = realFileName.substring(realFileName.lastIndexOf(".") + 1).toUpperCase();
JSONObject obj = new JSONObject();
/**
* 文件大小拦截,不能超过50M
*/
if (file.getSize() > (10 * 1024 * 1024 * config.getFileSize())) {
obj.put("error", 1);
result = "[ERROR]文件超过最大限制,请上传小于" + (200 * config.getFileSize()) + "M的文件";
} else if (config.getImageType().indexOf(suffix) < 0 && config.getFileType().indexOf(suffix) < 0) {
// 检查扩展名
obj.put("error", 1);
result = "[ERROR]上传文件格式不对";
} else {
// 检查扩展名
if (config.getImageType().indexOf(suffix) >= 0) {
saveUrl += "back/video";
} else {
saveUrl += "back/video";
}
String targetFileName = UUID.randomUUID().toString().replace("-", "") + "." + suffix;
// 保存图片
try {
if (!new File(destDir + saveUrl).exists()) {
new File(destDir + saveUrl).mkdirs();
}
File targetFile = new File(destDir + saveUrl, targetFileName);
file.transferTo(targetFile);
result = saveUrl + "/" + targetFileName;
obj.put("error", 0);
obj.put("state", "SUCCESS");
obj.put("url", result);
obj.put("src", config.getRootUrl() + result);
} catch (Exception e) {
obj.put("error", 1);
e.printStackTrace();
result = "[ERROR]上传失败";
}
}
if (!callBack.equals("")) {
if (result.indexOf("[ERROR]") < 0) {
// printMsg("<script>parent." + callBack + "('[OK]上传成功','" + result + "','" + property + "')</script>");
} else {
// printMsg("<script>parent.uploadImgCallBack('[ERROR]上传失败','" + result + "')</script>");
}
} else {
obj.put("message", result);
// printMsg(obj.toString());
}
return obj.toString();
}
@SuppressWarnings("unused")
@RequestMapping(value = "/file/uploadAndCut.do")
// @AuthPassport
public void uploadAndCut(@RequestParam(value = "file", required = false) CommonsMultipartFile file, int id,
String imageName, HttpServletRequest request) {
// 将request变成多部分request
String result = "";
String realFileName = file.getOriginalFilename();
String destDir = Tools.getServicePath(request);
String saveUrl = "upload/3d-141113221250/images";
String suffix = realFileName.substring(realFileName.lastIndexOf(".") + 1).toLowerCase();
JSONObject obj = new JSONObject();
/**
* 文件大小拦截,不能超过20M
*/
if (file.getSize() > 1024 * 1024 * config.getFileSize()) {
obj.put("error", 1);
result = "[ERROR]文件超过最大限制,请上传小于" + config.getFileSize() + "M的文件";
} else if (config.getImageType().indexOf(suffix) < 0 && config.getFileType().indexOf(suffix) < 0) {
// 检查扩展名
obj.put("error", 1);
result = "[ERROR]上传文件格式不对";
} else {
int x = 0;
int y = 0;
int width = 0;
int height = 0;
// 获取缩放或截图后图片的参数
String tailor = request.getParameter("tailor");
// 判断是否裁剪
if (!"false".equals(tailor)) {
// 裁剪
net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(tailor);
Map map = jsonObject;// new HashMap();
/*
* Map map = new HashMap<>(); JSONObject jsonObject = new
* JSONObject(tailor); for (Iterator iter = jsonObject.keys();
* iter.hasNext();) { String key = (String) iter.next();
* map.put(key, jsonObject.get(key)); }
*/
Double doubleX = (Double) map.get("x");
x = Integer.valueOf(doubleX.intValue());
Double doubleY = (Double) map.get("y");
y = Integer.valueOf(doubleY.intValue());
Double doubleWidth = (Double) map.get("width");
width = Integer.valueOf(doubleWidth.intValue());
Double doubleHeight = (Double) map.get("height");
height = Integer.valueOf(doubleHeight.intValue());
}
realFileName = id + "." + "png";
Rectangle rect = new Rectangle();
rect.setBounds(x, y, width, height);
// 縮放或裁剪
try {
if (!new File(destDir + saveUrl).exists()) {
new File(destDir + saveUrl).mkdirs();
}
File targetFile = new File(destDir + saveUrl, realFileName);
File srcFile = commonMultipartToFile(file);
ImageHepler.cutAndscaleImage(srcFile, targetFile, imageName, 640, 386, rect);
result = saveUrl + realFileName;
obj.put("error", 0);
obj.put("state", "SUCCESS");
obj.put("url", saveUrl + realFileName);
} catch (Exception e) {
obj.put("error", 1);
e.printStackTrace();
result = "[ERROR]上传失败";
}
}
}
/**
* MultipartFile 转换成File
*
* @param multfile
* 原文件类型
* @return File
* @throws IOException
*/
private File commonMultipartToFile(CommonsMultipartFile cf) throws IOException {
DiskFileItem fi = (DiskFileItem) cf.getFileItem();
File file = fi.getStoreLocation();
return file;
}
@RequestMapping(value = "/aaaa/uploadImage.do")
@ResponseBody
public Map<String, Object> uploadImage(@RequestParam(value = "upfile", required = false) CommonsMultipartFile upfile, HttpServletRequest request, HttpServletResponse response) {
Map<String, Object> params = new HashMap<String, Object>();
try{
String basePath = config.getRootPath();//存放根路径
String visitUrl = config.getRootUrl();//访问根路径
String realFileName = upfile.getOriginalFilename();//原名
String suffix = realFileName.substring(realFileName.lastIndexOf(".") + 1).toUpperCase();
String fileName = UUID.randomUUID().toString().replace("-", "") + "." + suffix;
StringBuilder sb = new StringBuilder();
//拼接保存路径
sb.append(basePath).append("back/picture/").append(fileName);
visitUrl = visitUrl + "back/picture/"+fileName;
File f = new File(sb.toString());
if(!f.exists()){
f.getParentFile().mkdirs();
}
OutputStream out = new FileOutputStream(f);
FileCopyUtils.copy(upfile.getInputStream(), out);
params.put("state", "SUCCESS");
params.put("url", visitUrl);
params.put("size", upfile.getSize());
params.put("original", fileName);
params.put("type", upfile.getContentType());
} catch (Exception e){
params.put("state", "ERROR");
}
return params;
}
}