package com.newfiber.api.pc.controller.News; import com.alibaba.fastjson.JSON; import com.newfiber.api.config.FileVisitProperty; import com.newfiber.api.core.annotation.SysLog; import com.newfiber.api.core.bean.RespBodyObj; import com.newfiber.api.core.exception.RRException; import com.newfiber.api.mobile.model.domain.RiverBusinessPics; import com.newfiber.api.pc.dao.EventsManage.ComplainPicDao; import com.newfiber.api.pc.dao.RiverManage.OfficialFileDao; import com.newfiber.api.pc.dao.RiverManage.RiverPicsDao; import com.newfiber.api.pc.model.EventsManage.ComplainPic; import com.newfiber.api.pc.model.River.OfficialFile; import com.newfiber.api.pc.model.River.RiverPics; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.apache.tomcat.util.http.fileupload.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; /** * 文件上传 * * @author chenshun * @email sunlightcs@gmail.com * @date 2017-03-25 12:13:26 */ @RestController @RequestMapping("/cloud") public class CloudController { private Logger logger = Logger.getLogger(CloudController.class); @Autowired private CloudStorageConfig config; /** 节点文件保存路径 */ @Value("${xnFile.path}") private String xnFilePath; /** 节点文件保存路径 */ @Value("${xnFile.pic}") private String xnPicPath; @Autowired private FileVisitProperty fileVisitProperty; @Autowired private RiverPicsDao riverPicsDao; @Autowired private OfficialFileDao officialFileDao; @Autowired private ComplainPicDao complainPicDao; private SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); /** * 上传文件 */ @PostMapping("/upload") @SysLog(value="上传文件",actionType="1") public String upload(@RequestParam("file") MultipartFile file) throws Exception { StringBuilder strBD = new StringBuilder(); strBD.append("|upload"); String imagePath = ""; try { if (file.isEmpty()) { throw new RRException("上传文件不能为空"); } } catch (Exception ex) { strBD.append("|ex:").append(ex.toString()); logger.error("", ex); } finally { logger.info(strBD.toString()); } return JSON.toJSONString(imagePath); } /** * 批量上传 * @param file * @return * @throws Exception */ @PostMapping("/uploadBatch") @SysLog(value="批量上传文件",actionType="1") public RespBodyObj upload(@RequestParam("file") MultipartFile[] file, HttpServletRequest request) throws Exception { StringBuilder strBD = new StringBuilder(); strBD.append("|upload"); String userNo = request.getHeader("userNo"); List<String> imagePath = new ArrayList<>(); List<RiverPics> result = new ArrayList<>(); if (file != null) { for (int i = 0; i < file.length; i++) { MultipartFile file1 = file[i]; String path = ""; try { String filename = file1.getOriginalFilename(); String suffix = filename.substring(filename.lastIndexOf(".")); Calendar instance = Calendar.getInstance(); //String filePath = instance.get(Calendar.YEAR) + File.separator +(instance.get(Calendar.MARCH) + 1) + File.separator + filename; StringBuffer sb = new StringBuffer(); sb.append(instance.get(Calendar.YEAR)) .append(File.separator) .append(instance.get(Calendar.MARCH) + 1). append(File.separator) .append(System.currentTimeMillis()).append(suffix); File fileName = new File(xnPicPath , sb.toString()); path = sb.toString(); if(!fileName.getParentFile().exists()){ fileName.mkdirs(); } try{ file1.transferTo(fileName); }catch (IOException e){ return RespBodyObj.error("上传失败"); } } catch (Exception ex) { strBD.append("|ex:").append(ex.toString()); logger.error("", ex); } finally { logger.info(strBD.toString()); } imagePath.add(path); } result = batchInsertImg(userNo, imagePath); } return RespBodyObj.ok(result); } /** * 批量保存图片 * @param userNo * @param imagePath */ private List<RiverPics> batchInsertImg(String userNo, List<String> imagePath) { List<RiverPics> result = new ArrayList<>(); try { if(!imagePath.isEmpty()){ for (String e : imagePath) { RiverPics riverPics = new RiverPics(); riverPics.setRiverPicsName(e); riverPics.setRiverPicsAddress(e); riverPics.setRealPath(fileVisitProperty.getWebPic()+e); riverPics.setCreateUserNo(userNo); riverPicsDao.insert(riverPics); result.add(riverPics); } } }catch (Exception e){ logger.info(e.toString()); } return result; } /** * 上传文件 */ @PostMapping("/uploadNew/{storeCode}/{type}") @SysLog(value="上传文件",actionType="1") public String uploadNew(@RequestParam("file") MultipartFile file, @PathVariable String storeCode, @PathVariable String type) throws Exception { StringBuilder strBD = new StringBuilder(); strBD.append("|uploadNew").append("|storeCode:").append(storeCode); strBD.append("|type").append(type); String imagePath = ""; try { if (file.isEmpty()) { throw new RRException("上传文件不能为空"); } try { // 重命名文件 // 获得原始文件名 String fileName = file.getOriginalFilename(); strBD.append("|fileName:").append(fileName); String suffix = getSuffix(fileName); // 重命名文件 String newfileName = sdf.format(new Date()) + "." + suffix; //把图片保存到本地 int bytesum = SaveFileFromInputStream(file.getInputStream(), config.getTmpDir(), newfileName); File newFile = new File(config.getTmpDir() + newfileName); strBD.append("|tmp:").append(config.getTmpDir()); strBD.append("|newfileName:").append(newfileName); strBD.append("|bytesum:").append(bytesum); if (newFile.exists() && newFile.isFile()) { strBD.append("|file exists"); imagePath = newfileName; //imagePath = COSClientManager.getInstance().putImageObject(newFile); // imagePath = COSClientManager.getInstance().putImageObject(storeCode,type,newFile); // //String destKey = COSClientManager.getInstance().copyBySrcKey(imagePath); // strBD.append("|imagePath:").append(imagePath); // //strBD.append("|destKey:").append(destKey); // try { // newFile.delete(); // strBD.append("|delete newFile"); // } catch (Exception e1) { // strBD.append("|delete error:").append(e1.toString()); // e1.printStackTrace(); // } } } catch (IOException e) { strBD.append("|e:").append(e.toString()); return null; } } catch (Exception ex) { strBD.append("|ex:").append(ex.toString()); logger.error("", ex); } finally { logger.info(strBD.toString()); } return JSON.toJSONString(imagePath); } /** * 获取扩展名 * * @param fileName * @return */ private String getSuffix(String fileName) { fileName = StringUtils.trimToEmpty(fileName); if (fileName.lastIndexOf(".") > 0 && fileName.length() > 1) { return fileName.substring(fileName.lastIndexOf(".") + 1); } return fileName; } public int SaveFileFromInputStream(InputStream stream, String path, String filename) throws IOException { FileOutputStream fs = null; int bytesum = 0; try { if (!path.endsWith("/")) { path += "/"; } fs = new FileOutputStream(path + filename); byte[] buffer = new byte[1024 * 1024]; int byteread = 0; while ((byteread = stream.read(buffer)) != -1) { bytesum += byteread; fs.write(buffer, 0, byteread); } fs.flush(); } catch (Exception e) { logger.error("", e); } finally { IOUtils.closeQuietly(fs); IOUtils.closeQuietly(stream); } return bytesum; } @PostMapping("/uploadFile") @SysLog(value="上传文件",actionType="1") public RespBodyObj uploadFile(@RequestParam("file") MultipartFile[] file, HttpServletRequest request) throws Exception { StringBuilder strBD = new StringBuilder(); strBD.append("|upload"); String userNo = request.getHeader("userNo"); List<String> imagePath = new ArrayList<>(); List<OfficialFile> result = new ArrayList<>(); if (file != null) { for (int i = 0; i < file.length; i++) { MultipartFile file1 = file[i]; String path = ""; String officeName = ""; try { String filename = file1.getOriginalFilename(); String suffix = filename.substring(filename.lastIndexOf(".")); officeName = filename; Calendar instance = Calendar.getInstance(); //String filePath = instance.get(Calendar.YEAR) + File.separator +(instance.get(Calendar.MARCH) + 1) + File.separator + filename; StringBuffer sb = new StringBuffer(); sb.append(instance.get(Calendar.YEAR)) .append(File.separator) .append(instance.get(Calendar.MARCH) + 1). append(File.separator) .append(System.currentTimeMillis()).append(suffix); File fileName = new File(xnFilePath , sb.toString()); path = sb.toString(); if(!fileName.getParentFile().exists()){ fileName.mkdirs(); } try{ file1.transferTo(fileName); }catch (IOException e){ return RespBodyObj.error("上传失败"); } } catch (Exception ex) { strBD.append("|ex:").append(ex.toString()); logger.error("", ex); } finally { logger.info(strBD.toString()); } OfficialFile filePath = new OfficialFile(); filePath.setCreateUserNo(userNo); filePath.setOfficialFileAddress(path); filePath.setOfficialName(officeName); result.add(filePath); } batchOfficeFile(result); } return RespBodyObj.ok(result); } private void batchOfficeFile(List<OfficialFile> imagePath) { List<OfficialFile> result = new ArrayList<>(); try { if(!imagePath.isEmpty()){ for (OfficialFile e : imagePath) { officialFileDao.insertSelective(e); } } }catch (Exception e){ logger.info(e.toString()); } } /** * 上传事件图片 * @param file * @param request * @return * @throws Exception */ @PostMapping("/uploadComplaintFile") @SysLog(value="上传事件图片",actionType="1") public RespBodyObj uploadComplaintFile(@RequestParam("file") MultipartFile[] file, HttpServletRequest request) throws Exception { StringBuilder strBD = new StringBuilder(); strBD.append("|upload"); String userNo = request.getHeader("userNo"); List<String> imagePath = new ArrayList<>(); List<ComplainPic> result = new ArrayList<>(); if (file != null) { for (int i = 0; i < file.length; i++) { MultipartFile file1 = file[i]; String path = ""; String officeName = ""; try { String filename = file1.getOriginalFilename(); String suffix = filename.substring(filename.lastIndexOf(".")); officeName = filename; Calendar instance = Calendar.getInstance(); //String filePath = instance.get(Calendar.YEAR) + File.separator +(instance.get(Calendar.MARCH) + 1) + File.separator + filename; StringBuffer sb = new StringBuffer(); sb.append(instance.get(Calendar.YEAR)) .append(File.separator) .append(instance.get(Calendar.MARCH) + 1). append(File.separator) .append(System.currentTimeMillis()).append(suffix); File fileName = new File(xnPicPath , sb.toString()); path = sb.toString(); if(!fileName.getParentFile().exists()){ fileName.mkdirs(); } try{ file1.transferTo(fileName); }catch (IOException e){ return RespBodyObj.error("上传失败"); } } catch (Exception ex) { strBD.append("|ex:").append(ex.toString()); logger.error("", ex); } finally { logger.info(strBD.toString()); } ComplainPic filePath = new ComplainPic(); filePath.setPicPath(path); filePath.setPicRealPath(fileVisitProperty.getWebPic()+path); filePath.setPicName(officeName); result.add(filePath); } } return RespBodyObj.ok(result); } /** * 河流问题图片 * @param file * @param request * @return * @throws Exception */ @PostMapping("/uploadRiverBussinessFile") @SysLog(value="河流问题图片",actionType="1") public RespBodyObj uploadRiverBussinessFile(@RequestParam("file") MultipartFile[] file, HttpServletRequest request) throws Exception { StringBuilder strBD = new StringBuilder(); strBD.append("|upload"); String userNo = request.getHeader("userNo"); List<String> imagePath = new ArrayList<>(); List<RiverBusinessPics> result = new ArrayList<>(); if (file != null) { for (int i = 0; i < file.length; i++) { MultipartFile file1 = file[i]; String path = ""; String officeName = ""; try { String filename = file1.getOriginalFilename(); String suffix = filename.substring(filename.lastIndexOf(".")); officeName = filename; Calendar instance = Calendar.getInstance(); //String filePath = instance.get(Calendar.YEAR) + File.separator +(instance.get(Calendar.MARCH) + 1) + File.separator + filename; StringBuffer sb = new StringBuffer(); sb.append(instance.get(Calendar.YEAR)) .append(File.separator) .append(instance.get(Calendar.MARCH) + 1). append(File.separator) .append(System.currentTimeMillis()).append(suffix); File fileName = new File(xnFilePath , sb.toString()); path = sb.toString(); if(!fileName.getParentFile().exists()){ fileName.mkdirs(); } try{ file1.transferTo(fileName); }catch (IOException e){ return RespBodyObj.error("上传失败"); } } catch (Exception ex) { strBD.append("|ex:").append(ex.toString()); logger.error("", ex); } finally { logger.info(strBD.toString()); } RiverBusinessPics filePath = new RiverBusinessPics(); filePath.setRiverPicsAddress(path); filePath.setRealPath(fileVisitProperty.getWebFile()+path); filePath.setRiverPicsName(officeName); result.add(filePath); } } return RespBodyObj.ok(result); } /** * 获取token * @param request * @param response * @param param * @return * @throws Exception */ /*@PostMapping(value = "getToken") @ResponseBody public String getToken(HttpServletRequest request, HttpServletResponse response, @RequestBody ReqBodyObj<Map<String,Object>> param)throws Exception{ String url = "http://server1.wh-nf.cn:8093/arcgis/tokens/generateToken"; List<NameValuePair> parameters = new ArrayList<NameValuePair>(); parameters.add(new BasicNameValuePair("username", (String) param.getData().get("username"))); parameters.add(new BasicNameValuePair("password", (String) param.getData().get("password"))); parameters.add(new BasicNameValuePair("client", "requestip")); parameters.add(new BasicNameValuePair("expiration", "90")); return HttpClienter.doPost1(url, parameters, request, response); }*/ }