package com.nationalelectric.greenH5;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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.MultipartFile;
import com.nationalelectirc.Constant.Constant;
import com.nationalelectirc.utils.RestResult;
import com.nationalelectirc.utils.Utils;
import com.nationalelectric.greenH5.utils.MD5Util;
import Decoder.BASE64Decoder;
import net.sf.json.JSONObject;
/**
* 概述:
*
*
* 功能:
* 图片上传
*
* @author MaYong
*/
@Controller
@RequestMapping("/greenFileUploadController")
public class GreenFileUploadController {
/**
* 文件上传
*
* @param file
* @param Request
* @param response
* @throws IOException
*/
/* @SuppressWarnings({ "unused" })
@RequestMapping(value = "/saveFileWeb", method = RequestMethod.POST)
@ResponseBody
public void savePersonPhoto(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request,
HttpServletResponse response) throws IOException {
String requestUrl = request.getRequestURL().toString();
String requestUri = request.getRequestURI().toString();
String contextPath = request.getContextPath();
// String url = requestUrl.replace(requestUri, "");
String url = PropertyUtil.getValue("webImageUrl");
// url = url + contextPath;
HashMap ret = new HashMap();
try {
List> companyInfoList = new ArrayList>();
String exName = "";
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
String projectPath = request.getSession().getServletContext().getRealPath("");
System.out.println("== projectPath:" + projectPath);
if (projectPath.endsWith(File.separator)) {
projectPath = projectPath.substring(0, projectPath.length() - 1);
}
System.out.println("======= 111:" + projectPath);
String webappPath = projectPath.substring(0, projectPath.lastIndexOf(File.separator));
System.out.println("======= webappPath:" + webappPath);
// String directoryPath = webappPath + File.separator + "greenfile"
// + File.separator;
String directoryPath = PropertyUtil.getValue("saveImagePath");
System.out.println("======= directoryPath:" + directoryPath);
if (file.getOriginalFilename().lastIndexOf(".") != -1) {
exName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
}
exName = "." + exName.toLowerCase();
String fileName = uuid + exName;
String path = directoryPath;
// path = getParentDirPath(path);
File targetFile = new File(path, fileName);
// 濡拷濞村娲伴弽鍥ㄦ瀮娴犺埖妲搁崥锕�鐡ㄩ崷顭掔礉娑撳秴鐡ㄩ崷銊ュ灟閸掓稑缂撻弬鍥︽婢讹拷
if (!targetFile.exists())
targetFile.mkdirs();
file.transferTo(targetFile);
String md5str = MD5Util.getFileMD5String(targetFile);
System.out.println("========== file md5:" + md5str);
ret.put("success", "200");
ret.put("filePath", url + "/greenfile/" + fileName);
System.out.println("======= filePath:" + url + "/greenfile/" + fileName);
ret.put("path", "/greenfile/" + fileName);
} catch (Exception e) {
}
response.getWriter().print(JSONObject.fromObject(ret).toString());
}
*/
/**
* 文件上传
*
* @param file
* @param Request
* @param response
* @throws IOException
*/
@SuppressWarnings({ "unused" })
@RequestMapping(value = "/saveFile", method = RequestMethod.POST)
@ResponseBody
public void saveFileBase64(HttpServletRequest request, HttpServletResponse response) throws IOException {
// 取图片BASE64数据
byte buffer[] = getRequestPostBytes(request);
/*
* Base64.Decoder decoder = Base64.getDecoder(); byte[] str
* =decoder.decode(buffer); String jsonStr1 = new String(str); String
* jsonStr=URLDecoder.decode(jsonStr1, "utf-8");
*/
String bodyStr = new String(buffer,"UTF-8");
JSONObject jsonObject = JSONObject.fromObject(bodyStr);
String fileStr = jsonObject.getString("file");
String checkTime = jsonObject.getString("checkTime");
if(Utils.list.contains("greenFileUploadController/saveFile"+checkTime)){
return ;
}else{
Utils.list.add("greenFileUploadController/saveFile"+checkTime);
}
// 取图片路径相关信息
// String requestUrl = request.getRequestURL().toString();
// String requestUri = request.getRequestURI().toString();
// String contextPath = request.getContextPath();
// String url = requestUrl.replace(requestUri, "");
String url = "http://47.111.188.136:17001";
// url = url + contextPath;
HashMap ret = new HashMap();
try {
// List> companyInfoList = new ArrayList>();
// String exName = "";
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
// String projectPath = request.getSession().getServletContext().getRealPath("");
//
// if (projectPath.endsWith(File.separator)) {
// projectPath = projectPath.substring(0, projectPath.length() - 1);
// }
//String webappPath = projectPath.substring(0, projectPath.lastIndexOf(File.separator));
// String directoryPath = webappPath + File.separator + "greenfile"
// + File.separator;
//String directoryPath = "/home/greenfile/";
// 写死路径 防止报Path Manipulation
String fileName = uuid + ".jpg";
String path = "/home/greenfile/";
// path = getParentDirPath(path);
File targetFile = new File(path);
// 检测目标文件是否存在,不存在则创建文件夹
if (!targetFile.exists())
targetFile.mkdirs();
// file.transferTo(targetFile);
GenerateImage(fileStr, path, getFilePath(fileName));
ret.put("success", "200");
ret.put("filePath", url + "/greenfile/" + fileName);
ret.put("path", "/greenfile/" + fileName);
} catch (Exception e) {
e.printStackTrace();
}
ret.put("success", "500");
response.getWriter().print(JSONObject.fromObject(ret).toString());
}
public String getFilePath(String path){
HashMap map = new HashMap();
map.put("a", "a");
map.put("b", "b");
map.put("c", "c");
map.put("d", "d");
map.put("e", "e");
map.put("f", "f");
map.put("g", "g");
map.put("h", "h");
map.put("i", "i");
map.put("j", "j");
map.put("k", "k");
map.put("l", "l");
map.put("m", "m");
map.put("n", "n");
map.put("o", "o");
map.put("p", "p");
map.put("q", "q");
map.put("r", "r");
map.put("s", "s");
map.put("t", "t");
map.put("u", "u");
map.put("v", "v");
map.put("w", "w");
map.put("x", "x");
map.put("y", "y");
map.put("z", "z");
map.put("A", "A");
map.put("B", "B");
map.put("C", "C");
map.put("D", "D");
map.put("E", "E");
map.put("F", "F");
map.put("G", "G");
map.put("H", "H");
map.put("I", "I");
map.put("J", "J");
map.put("K", "K");
map.put("L", "L");
map.put("M", "M");
map.put("N", "N");
map.put("O", "O");
map.put("P", "P");
map.put("Q", "Q");
map.put("R", "R");
map.put("S", "S");
map.put("T", "T");
map.put("U", "U");
map.put("V", "V");
map.put("W", "W");
map.put("X", "X");
map.put("Y", "Y");
map.put("Z", "Z");
map.put(":", ":");
map.put("/", "/");
map.put("\\", "\\");
String temp = "";
for (int i = 0; i < path.length(); i++) {
if (map.get(path.charAt(i)+"")!=null) {
temp += map.get(path.charAt(i)+"");
}
}
path = temp;
return path;
}
/**
* 描述:获取 post 请求的 byte[] 数组
*
*
* 举例:
*
*
* @param request
* @return
* @throws IOException
*/
public static byte[] getRequestPostBytes(HttpServletRequest request) throws IOException {
int contentLength = request.getContentLength();
if (contentLength < 0) {
return null;
}
byte buffer[] = new byte[contentLength];
for (int i = 0; i < contentLength;) {
int readlen = request.getInputStream().read(buffer, i, contentLength - i);
if (readlen == -1) {
break;
}
i += readlen;
}
return buffer;
}
// base64字符串转化成图片
public boolean GenerateImage(String imgStr, String filePath, String fileName) throws IOException { // 鐎电懓鐡ч懞鍌涙殶缂佸嫬鐡х粭锔胯鏉╂稖顢態ase64鐟欙絿鐖滈獮鍓佹晸閹存劕娴橀悧锟�
// System.out.println(imgStr);
OutputStream out = null;
if (imgStr == null) // 图像数据为空
return false;
imgStr = imgStr.substring(imgStr.indexOf(",") + 1);
// System.out.println(imgStr);
BASE64Decoder decoder = new BASE64Decoder();
try {
// Base64解码
byte[] b = decoder.decodeBuffer(imgStr);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {// 调整异常数据
b[i] += 256;
}
}
// 生成jpeg图片 以下操作防止报Path Manipulation
if (fileName.contains("../")) {
return false;
}
String path1 = "/home/greenfile/" + fileName;
if (path1.contains("../")) {
return false;
}
out = new FileOutputStream("/home/greenfile/"+getFilePath(fileName));
out.write(b);
out.flush();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
if (out != null) {
out.close();
}
}
}
}