//download.html
图片分页预览
//download.js
var trId=window.parent.trId;
$(function() {
if(trId!=null&&trId!=""){
initImg();
}else{
var arr=null;
appendImgList(arr);
}
initSwiper();
})
//初始化img
function initImg() {
var result = [];
$.ajax({
type: "get",
async: false,
url: $GATEWAY_URL + "/upImgController/downloadImage/" + trId,
success: function(data, status) {
if(data != null && data.length > 0) {
for(var i = 0; i < data.length; i++) {
result[i] = data[i];
}
appendImgList(result);
} else {
appendImgList(result);
}
},
error: function(data) {
appendImgList(result);
}
});
}
//文件删除
function over(param) {
layer.confirm('您确定要删除该图片吗?', {
btn: ['确定', '取消'] //按钮
}, function() {
$.ajax({
type: "get",
async: false,
//图片删除
//url: $GATEWAY_URL + "/upImgController/removeImage/" + trId+"/"+param,
url: $GATEWAY_URL + "/upImgController/removeImage/"+param,
success: function(data, status) {
layer.msg(data.msg);
window.location.reload();
},
error: function(data) {
layer.msg(data.msg);
//appendImgList(result);
}
});
}, function() {
});
return false;
}
//导出全部
function exportAll() {
window.location.href = $GATEWAY_URL + "/upImgController/fileDownLoad/?trId=" + trId;
}
function appendImgList(result) {
//华为云改造
//var imgUrl = $GATEWAY_URL + "/upImgController/IoReadImage/" + trId + "/";
var imgUrl = $GATEWAY_URL + "/upImgController/IoReadImage/";
if(result != null && result.length > 0) {
$(".swiper-wrapper").empty();
//当图片数量小于3时 补充空白图片
if(result.length < 3) {
for(var i = 0; i < 3; i++) {
if(i < result.length) {
$(".swiper-wrapper").append("
");
} else {
$(".swiper-wrapper").append("");
}
}
} else {
for(var i = 0; i < result.length; i++) {
$(".swiper-wrapper").append(" ");
}
}
} else {
$(".swiper-wrapper").append("");
$(".swiper-wrapper").append("");
$(".swiper-wrapper").append("");
}
$(".pic").bind("contextmenu",function(e){
return false;
});
}
//初始化swiper
function initSwiper() {
var swiper = new Swiper('.swiper-container', {
slidesPerView: 3,
spaceBetween: 30,
centeredSlides: true,
loop: true,
pagination: {
el: '.swiper-pagination',
clickable: true,
},
});
}
//upload.html
webupload多张图片批量上传插件
最多上传8张图片(单张小于25M)格式:(*.gif,*.jpg,*.jpeg,*.png)
var fileArr = [];
var trId;
$(function() {
var getUrl = encodeURI(window.location.search).split("&");
trId = getUrl[0].split("=")[1];
var imgFile = new ImgUploadeFiles('.imgupBox', function(e) {
this.init({
MAX: 10, //限制个数
MH: 5800, //像素限制高度
MW: 5900, //像素限制宽度
callback: function(arr) {
console.log(arr)
}
});
});
})
/*
* 上传图片
* */
function multipleFiles() {
//补充说明:因为我们给input标签设置multiple属性,因此一次可以上传多个文件
//获取选择图片数组
var files = fileArr;
//获取选择图片的个数
var length = files.length;
if(length == 0) {
alert("请选择需要上传的图片!");
return;
}
var fu = new FormData();
for(var i = 0; i < files.length; i++) { //循环获取多个文件
fu.append("file", files[i]);
}
fu.append("trId", trId);
$.ajax({
type: "post",
url: $GATEWAY_URL+"/upImgController/uploadimgs",
data: fu,
cache: false,
contentType: false, //不可缺参数
processData: false, //不可缺参数
success: function(data, status) {
window.top.layer.msg(data.msg);
parent.location.reload();//刷新父页面
var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
parent.layer.close(index); //再执行关闭
},
error: function(data) {
window.top.layer.msg("图片上传失败:"+data.msg);
},
complete: function() {}
});
}
//导出全部
function exportAll() {
window.location.href = $GATEWAY_URL + "/upImgController/fileDownLoad/?trId=" + trId;
}
可以百度或者华为云官网 搜索 “华为云 obs SDK springboot 集成”
com.huaweicloud
esdk-obs-java
3.20.6.1
package com.nari.osp.upload.util;
import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* @author xxx
* @createTime 2021/12/6 16:31
* @description 华为OBS工具类
*/
@Slf4j @Component @RefreshScope public class HuaweiOBSUtil {
private static String endPoint;
private static String ak;
private static String sk;
private static String bucketName;
@Value("${obs.endPoint}") public void setEndPoint(String endPoint) {
HuaweiOBSUtil.endPoint = endPoint;
}
@Value("${obs.ak}") public void setAk(String ak) {
HuaweiOBSUtil.ak = ak;
}
@Value("${obs.sk}") public void setSk(String sk) {
HuaweiOBSUtil.sk = sk;
}
@Value("${obs.bucketName}") public void setBucketName(String bucketName) {
HuaweiOBSUtil.bucketName = bucketName;
}
/**
* 上传File类型文件
*
* @param file
* @return
*/
public static String uploadFile(File file, String trId) {
return getUploadFileUrl(file, trId);
}
/**
* 上传MultipartFile类型文件
*
* @param multipartFile
* @return
*/
public static String uploadFile(MultipartFile multipartFile, String trId) throws IOException {
return getUploadFileUrl(FileUtils.MultipartFileToFile(multipartFile), trId);
}
private static String getUploadFileUrl(File file, String trId) {
//判断文件是否为空
if (FileUtils.checkFileNotNull(file)) {
//获取文件名称
String fileName = FileUtils.getName(file);
log.info("上传图片名称:" + fileName + "ak:" + ak + "sk:" + sk + "endPoint:" + endPoint);
//创建华为云obs对象
ObsClient obsClient = new ObsClient(ak, sk, endPoint);
try {
//判断桶是否存在,不存在则创建
if (!obsClient.headBucket(bucketName)) {
obsClient.createBucket(bucketName);
}
//拼接前缀对象 形成目录 380xxx/a.jpeg
PutObjectRequest request = new PutObjectRequest();
request.setBucketName(bucketName);
request.setObjectKey(trId + "/" + fileName);
request.setFile(file);
request.setAcl(AccessControlList.REST_CANNED_PUBLIC_READ);
PutObjectResult result = obsClient.putObject(request);
String url = result.getObjectUrl();
log.info("图片路径:" + url);
return url;
} catch (Exception e) {
log.error("图片上传错误:{}", e);
}/* finally {
删除本地临时文件
HuaweiOBSUtil.deleteTempFile(file);
}*/
}
return null;
}
/**
* 根据文件夹 地址获取文件夹 IO流
*
* @param localPath 本地临时存储下载文件路径
* @param trId 配变编号 对应 obs平台 文件夹名称
* @return
*/
public static void downloadDirIOByUrl(String localPath, String trId) {
try {
//String fileLocatePrefix = localPath;
// 创建ObsClient实例
ObsClient obsClient = new ObsClient(ak, sk, endPoint);
ListObjectsRequest request = new ListObjectsRequest(bucketName);
// 指定下载"FunctionGraphDemo-VideoConvert/"文件夹
request.setPrefix(trId);
request.setMaxKeys(500);
ObjectListing result;
log.info("本地文件临时存储路径fileLocatePrefix:" + localPath);
do {
result = obsClient.listObjects(request);
for (ObsObject obsObject : result.getObjects()) {
log.info("获取obs图片:" + obsObject.getObjectKey());
DownloadFileRequest requestDownload = new DownloadFileRequest(bucketName, obsObject.getObjectKey());
String objectKey = getFilenameByUrlV2(obsObject.getObjectKey());
requestDownload.setDownloadFile(localPath + "//" + objectKey);
// 设置分段下载时的最大并发数
requestDownload.setTaskNum(10);
// 设置分段大小为10MB
requestDownload.setPartSize(10 * 1024 * 1024);
// 开启断点续传模式
requestDownload.setEnableCheckpoint(true);
try {
// 进行断点续传下载
obsClient.downloadFile(requestDownload);
} catch (ObsException e) {
log.info("Response Code: " + e.getResponseCode());
log.info("Error Message: " + e.getErrorMessage());
log.info("Error Code: " + e.getErrorCode());
log.info("Request ID: " + e.getErrorRequestId());
log.info("Host ID: " + e.getErrorHostId());
}
}
log.info("------------------------------");
request.setMarker(result.getNextMarker());
} while (result.isTruncated());
} catch (ObsException e) {
log.error("文件下载失败:{}", e.getMessage());
}
}
/**
* 根据文件地址获取桶对象
*
* @param trId
* @return
*/
public static List getBucketObjectList(String trId) {
List result = new ArrayList<>();
try {
//创建ObsClient实例
ObsClient obsClient = new ObsClient(ak, sk, endPoint);
/*
* String bucketName, 桶
* String prefix, 前缀 abcd abcde bbced prefix 为a 则 abcd abcde 一组 bbced为一组
* String marker,
* String delimiter,
* int maxKeys 返回最大列表数量
* */
ObjectListing objectListing = obsClient.listObjects(new ListObjectsRequest(bucketName, trId, "", "", 1000));
//列举桶内所有对象
//ObjectListing objectListing = obsClient.listObjects(bucketName);
List objects = objectListing.getObjects();
log.info("获取桶内所有对象集合大小为:" + objects.size());
for (ObsObject obj : objects) {
String objectKey = obj.getObjectKey();
if (objectKey.contains(trId)) {
result.add(objectKey);
}
}
return result;
} catch (ObsException e) {
log.error("文件下载失败:{}", e.getMessage());
}
return null;
}
/**
* 根据文件地址获取文件IO流
*
* @param fileUrl
* @return
*/
public static InputStream downloadFileIOByUrl(String fileUrl) {
try {
//获取文件名称
String fileName = getFilenameByUrl(fileUrl);
// 创建ObsClient实例
ObsClient obsClient = new ObsClient(ak, sk, endPoint);
ObsObject obsObject = obsClient.getObject(bucketName, fileName);
InputStream inputStream = obsObject.getObjectContent();
//转成MultipartFile
//MultipartFile multipartFile = InputStreamConvertMultipartFileUtil.getMultipartFile(inputStream, fileName);
//File file = com.xxx.util.FileUtil.MultipartFileToFile(multipartFile);
return inputStream;
} catch (ObsException e) {
log.error("文件下载失败:{}", e.getMessage());
}
return null;
}
/**
* 删除单个对象
*
* @param objectKey
* @return
*/
public static boolean deleteFile(String objectKey) {
ObsClient obsClient = new ObsClient(ak, sk, endPoint);
DeleteObjectResult deleteObjectResult = obsClient.deleteObject(bucketName, objectKey);
boolean deleteMarker = deleteObjectResult.isDeleteMarker();
try {
obsClient.close();
} catch (IOException e) {
log.error("华为OBS关闭客户端失败", e);
}
return deleteMarker;
}
/**
* 上传图片自定义code
*
* @param ak
* @param sk
* @param endPoint
* @param file
* @return
*/
public static String uploadFileByCode(String ak, String sk, String endPoint, String bucket, File file) {
//String pathname = objectName;
try {
String fileName = FileUtils.getName(file);
log.info("上传图片:" + fileName);
ObsClient obsClient = new ObsClient(ak, sk, endPoint);
//判断桶是否存在,不存在则创建
if (!obsClient.headBucket(bucket)) {
obsClient.createBucket(bucket);
}
PutObjectRequest request = new PutObjectRequest();
request.setBucketName(bucket);
request.setObjectKey(fileName);
request.setFile(file);
request.setAcl(AccessControlList.REST_CANNED_PUBLIC_READ);
PutObjectResult result = obsClient.putObject(request);
String url = result.getObjectUrl();
log.info("文件名称:" + fileName + "图片路径:" + url);
return url;
} catch (Exception e) {
log.error("图片上传错误:{}", e);
} /*finally {
HuaweiOBSUtil.deleteTempFile(file);
}*/
return null;
}
/**
* 删除本地临时文件
*
* @param file
*/
public static void deleteTempFile(File file) {
if (file != null) {
File del = new File(file.toURI());
del.delete();
}
}
/**
* 根据文件地址获取名称下载File类型的文件
*
* @param fileUrl
* @return
*/
public static MultipartFile downloadFileByUrl(String fileUrl) {
try {
String fileName = getFilenameByUrl(fileUrl);
// 创建ObsClient实例
ObsClient obsClient = new ObsClient(ak, sk, endPoint);
ObsObject obsObject = obsClient.getObject(bucketName, fileName);
InputStream inputStream = obsObject.getObjectContent();
//转成MultipartFile
MultipartFile multipartFile = InputStreamConvertMultipartFileUtil.getMultipartFile(inputStream, fileName);
//File file = com.xxx.util.FileUtil.MultipartFileToFile(multipartFile);
return multipartFile;
} catch (ObsException e) {
log.error("文件下载失败:{}", e.getMessage());
}
return null;
}
/**
* 批量n天删除之前的文件
*
* @param ak
* @param sk
* @param endPoint
* @param bucket
* @param requireHours
*/
public static void batchDeleteForHoursago(String ak, String sk, String endPoint, String bucket, int requireHours) {
ObsClient obsClient = new ObsClient(ak, sk, endPoint);
long currentTime = new Date().getTime();
try {
ListObjectsRequest listRequest = new ListObjectsRequest(bucket);
listRequest.setMaxKeys(1000); // 每次至多返回1000个对象
ObjectListing listResult;
Date lastModified;
long hourMillisecond = 1000 * 3600 * 1;
// 分页查询
do {
List toDelete = new ArrayList<>();
listResult = obsClient.listObjects(listRequest);
for (ObsObject obsObject : listResult.getObjects()) {
lastModified = obsObject.getMetadata().getLastModified();
long diffs = (currentTime - lastModified.getTime()) / hourMillisecond; // 当前时间减去文件修改时间
if (diffs > requireHours && (obsObject.getObjectKey().endsWith(".ts") || obsObject.getObjectKey()
.endsWith(".mp4"))) {
log.info("文件距现在{}小时,对象更改日期:{},文件对象:{}", diffs, lastModified, obsObject.getObjectKey());
toDelete.add(new KeyAndVersion(obsObject.getObjectKey()));
}
}
// 设置下次列举的起始位置
listRequest.setMarker(listResult.getNextMarker());
//批量删除文件
log.info("待删除的OBS对象数量:{}", toDelete.size());
if (!CollectionUtils.isEmpty(toDelete)) {
DeleteObjectsRequest deleteRequest = new DeleteObjectsRequest(bucket);
deleteRequest.setQuiet(true); // 设置为quiet模式,只返回删除失败的对象
deleteRequest.setKeyAndVersions(toDelete.toArray(new KeyAndVersion[toDelete.size()]));
DeleteObjectsResult deleteResult = obsClient.deleteObjects(deleteRequest);
if (!CollectionUtils.isEmpty(deleteResult.getErrorResults())) {
log.error("删除失败的OBS对象数量:{}", deleteResult.getErrorResults().size());
}
}
} while (listResult.isTruncated());
} catch (Exception e) {
log.error("华为OBS批量删除异常", e);
} finally {
try {
obsClient.close();
} catch (IOException e) {
log.error("华为OBS关闭客户端失败", e);
}
}
}
/**
* 查询桶内已使用空间大小
*
* @param ak
* @param sk
* @param endPoint
* @param bucket
* @return 单位字节
*/
public static long getBucketUseSize(String ak, String sk, String endPoint, String bucket) {
ObsClient obsClient = new ObsClient(ak, sk, endPoint);
BucketStorageInfo storageInfo = obsClient.getBucketStorageInfo(bucket);
log.info("{} 桶内对象数:{} 已使用的空间大小B:{} GB:{}", bucket, storageInfo.getObjectNumber(), storageInfo.getSize(),
storageInfo.getSize() / 1024 / 1024 / 1024);
try {
obsClient.close();
} catch (IOException e) {
log.error("华为OBS关闭客户端失败", e);
}
return storageInfo.getSize();
}
public static String readFileContent(String fileName) {
File file = new File(fileName);
BufferedReader reader = null;
StringBuffer sbf = new StringBuffer();
try {
reader = new BufferedReader(new FileReader(file));
String tempStr;
while ((tempStr = reader.readLine()) != null) {
sbf.append(tempStr);
}
reader.close();
return sbf.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
return sbf.toString();
}
/**
* 根据下载地址url获取文件名称
*
* @param url
* @throws IOException
*/
public static String getFilenameByUrl(String url) {
String fileName = null;
try {
//url编码处理,中文名称会变成百分号编码
//String decode = URLDecoder.decode(url, "utf-8");
fileName = URLDecoder.decode(url, "utf-8");
//fileName = decode.substring(decode.lastIndexOf("/") + 1);
log.info("fileName :" + fileName);
} catch (UnsupportedEncodingException e) {
log.error("getFilenameByUrl() called with exception => 【url = {}】", url, e);
e.printStackTrace();
}
return fileName;
}
/**
* 根据下载地址url获取文件名称
*
* @param url
* @throws IOException
*/
public static String getFilenameByUrlV2(String url) {
String fileName = null;
try {
//url编码处理,中文名称会变成百分号编码
String decode = URLDecoder.decode(url, "utf-8");
fileName = decode.substring(decode.lastIndexOf("/") + 1);
log.info("fileName :" + fileName);
} catch (UnsupportedEncodingException e) {
log.error("getFilenameByUrl() called with exception => 【url = {}】", url, e);
e.printStackTrace();
}
return fileName;
}
}
package com.nari.osp.upload.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSchException;
import com.nari.osp.upload.entity.ApolloConfig;
import com.nari.osp.upload.entity.QueryCondition;
import com.nari.osp.upload.entity.TrBaseEntity;
import com.nari.osp.upload.service.impl.ObsUpImgServiceImpl;
import com.nari.osp.upload.service.impl.UpImgServiceImp;
import com.nari.osp.upload.util.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;
@CrossOrigin(origins = "*", maxAge = 3600) @Controller @RequestMapping("/upImgController")
@SuppressWarnings(value = "all") public class UpImgController {
Log log = LogFactory.getLog(getClass());
@Autowired private ApolloConfig apolloConfig;
@Autowired private UpImgServiceImp upImgService;
@Autowired private ObsUpImgServiceImpl cbsUpImgService;
//图片流(废弃)
//Map imgIO = new HashMap<>();
ChannelSftp ftpClient = null;
/*
* 查询配变台账 判断此配变是否上传图片
* @param files
* @return
* */
//负载率统计
@ResponseBody @RequestMapping("/getTrBaseList") public JSONObject getTrBaseList(QueryCondition queryParam) {
return upImgService.getTrBaseList(queryParam);
}
/*
* 查询配变台账
* @param files
* @return
* */
//负载率统计
@ResponseBody @RequestMapping("/getTrBase") public TrBaseEntity getTrBase(QueryCondition queryParam) {
return upImgService.getTrBase(queryParam);
}
/**
* 图片保存至服务器(无ftp传输)
*
* @param
* @return
*/
@RequestMapping("/imgUpload/{trId}") public @ResponseBody void imgUpload(HttpServletRequest request,
HttpServletResponse response, @PathVariable String trId) throws Exception {
//是否华为云cbs存储
if (apolloConfig.isObs()) {
cbsUpImgService.imgUpload(request, response, trId);
} else {
upImgService.imgUpload(request, response, trId);
}
}
/**
* IO流读取图片集合
*
* @param
* @return
*/
@RequestMapping(value = "/downloadImage/{trid}", method = RequestMethod.GET) @ResponseBody
public List downloadImage(@PathVariable String trid) throws Exception {
List imgName;
//是否华为云cbs存储
if (apolloConfig.isObs()) {
imgName = cbsUpImgService.downloadImage(trid);
} else {
imgName = upImgService.downloadImage(trid);
}
return imgName;
}
/*
* 图片访问地址
* */
@RequestMapping(value = "/IoReadImage/{trid}/{imgId}", method = RequestMethod.GET) public void IoReadImage(
@PathVariable String trid, @PathVariable String imgId, HttpServletResponse response) throws Exception {
//是否华为云cbs存储
if (apolloConfig.isObs()) {
cbsUpImgService.IoReadImage(trid, imgId, response);
} else {
upImgService.IoReadImage(trid, imgId, response);
}
}
/*
* 图片删除
* */
@ResponseBody @RequestMapping(value = "/removeImage/{trid}/{imgId}", method = RequestMethod.GET)
public ResponseData removeImage(@PathVariable String trid, @PathVariable String imgId, HttpServletResponse response)
throws Exception {
//是否华为云cbs存储
ResponseData responseData;
if (apolloConfig.isObs()) {
responseData = cbsUpImgService.removeImage(trid, imgId, response);
} else {
responseData = upImgService.removeImage(trid, imgId, response);
}
return responseData;
}
/*
* 文件下载 zip 图片 文档
* */
@ResponseBody @RequestMapping("/fileDownLoad") public void fileDownload(@RequestParam("trId") String trId,
HttpServletRequest request, HttpServletResponse response) throws IOException {
//是否华为云cbs存储
if (apolloConfig.isObs()) {
cbsUpImgService.fileDownload(trId, request, response);
} else {
upImgService.fileDownload(trId, request, response);
}
}
@ResponseBody @RequestMapping("/exportExcel")
public void exportExcel(@RequestParam("param") String param, HttpServletResponse response) {
QueryCondition queryParam = JSON.parseObject(param, QueryCondition.class);
queryParam.setPage(0);
queryParam.setRows(65000);
//QueryCondition queryParam =new QueryCondition();
// "CT变比", "配变容量(KVA)", "可靠性"};
String[] headers = {"地市公司", "区县公司", "所属馈线", "所属厂站", "配变编号", "配变名称", "PMS编码", "是否上传图片"};
// “0,2,0,0” ===> “起始行,截止行,起始列,截止列”
String fileName = "电压负载率明细" + ".xls";
//String version = pbqxCondition.getVersion();
JSONObject jsonObject = upImgService.getTrBaseList(queryParam);
JSONArray list = jsonObject.getJSONArray("rows");
int rowIndex = 0;
HSSFWorkbook wb = null; //03
XSSFWorkbook xwb = null; //07
// 第一步,创建一个webbook,对应一个Excel文件
xwb = new XSSFWorkbook();
XSSFSheet xsheet = xwb.createSheet("图片列表");
XSSFRow row = xsheet.createRow(rowIndex++);
// 简单表头
for (int i = 0; i < headers.length; i++) {
xsheet.autoSizeColumn(i, true);
row.createCell(i).setCellValue(headers[i]);
}
//加载数据
for (int i = 0; i < list.size(); i++) {
JSONObject json = list.getJSONObject(i);
row = xsheet.createRow(rowIndex++);
//row = sheet.createRow(rowIndex++);
//String[] str=list.get(i).split(",");
row.createCell(0).setCellValue(json.getString("orgname03").equals("") ? "-" : json.getString("orgname03"));
row.createCell(1).setCellValue(json.getString("orgname04").equals("") ? "-" : json.getString("orgname04"));
row.createCell(2).setCellValue(json.getString("lineName").equals("") ? "-" : json.getString("lineName"));
row.createCell(3).setCellValue(json.getString("subName").equals("") ? "-" : json.getString("subName"));
row.createCell(4).setCellValue(json.getString("trNo").equals("") ? "-" : json.getString("trNo"));
row.createCell(5).setCellValue(json.getString("trName").equals("") ? "-" : json.getString("trName"));
row.createCell(6).setCellValue(json.getString("pmsId").equals("") ? "-" : json.getString("pmsId"));
String isUpload = json.getString("isUpload");
if (!"".equals(isUpload) && "true".equals(isUpload)) {
row.createCell(7).setCellValue("是");
} else {
row.createCell(7).setCellValue("否");
}
//String kykxTemp = !"可信".equals(list.get(i).getKeyFlag()) ? "可疑" : "可信";
//row.createCell(9).setCellValue(list.get(i).getKeyFlag() != "可信" ? "可疑" : "可信");
//row.createCell(9).setCellValue(kykxTemp);
}
try {
//导出数据
response.setHeader("Content-Disposition",
"attachment;filename=" + new String(fileName.getBytes("utf-8"), "iso8859-1"));
response.setContentType("application/ynd.ms-excel;charset=UTF-8");
OutputStream out = response.getOutputStream();
xwb.write(out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* IO流读取图片集合 并发送至前端 imgTemp文件夹(废弃)
*
* @param
* @return
*/
@RequestMapping(value = "/downloadImageV2/{trid}", method = RequestMethod.GET) @ResponseBody
public List downloadImageV2(@PathVariable String trid) throws Exception {
List imgName = new ArrayList<>();
//服务器文件
String ftpPath = apolloConfig.getFilePath();
//本地临时文件 前台代码吧 imgTemp
String localPath = apolloConfig.getLFilePath();
try {
//连接远程sftp
ftpClient = JcraftTools.getConnect(apolloConfig.getIp(), apolloConfig.getPort(), apolloConfig.getUsername(),
apolloConfig.getPassword());
Vector ftpFiles = ftpClient.ls(ftpPath + trid);
if (ftpFiles != null && ftpFiles.size() > 0) {
for (ChannelSftp.LsEntry lsEntry : ftpFiles) {
//临时e文件名称
String fileTemp = lsEntry.getFilename();
if (fileTemp.contains(".png") || fileTemp.contains(".jpg") || fileTemp.contains(".jpeg")) {
imgName.add(fileTemp);
JcraftTools.download(ftpPath + trid, localPath, fileTemp, fileTemp);
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//记得关闭连接
if (ftpClient != null) {
ftpClient.quit();
ftpClient.disconnect();
try {
if (ftpClient.getSession() != null)
ftpClient.getSession().disconnect();
} catch (JSchException e) {
log.error("channel getSession error:", e);
}
}
}
return imgName;
}
/**
* 删除前台临时存放图片(废弃)
*
* @param
* @return
*/
public void removeWebDir() throws Exception {
//E文件解析工具类
ChannelSftp ftpClient = null;
try {
//连接远程sftp
ftpClient = JcraftTools
.getConnect(apolloConfig.getLIp(), apolloConfig.getLPort(), apolloConfig.getLUsername(),
apolloConfig.getLPassword());
log.info("清除定时任务------已连接远程服务器!");
// 删除指定文件下的所有文件
Vector ftpFiles = ftpClient.ls(apolloConfig.getLFilePath());
if (ftpFiles != null && ftpFiles.size() > 0) {
for (ChannelSftp.LsEntry lsEntry : ftpFiles) {
//临时e文件名称
String fileTemp = lsEntry.getFilename();
if (fileTemp.contains(".png") || fileTemp.contains(".jpg")) {
ftpClient.rm(apolloConfig.getLFilePath() + "/" + fileTemp);
log.info("文件已删除:" + apolloConfig.getLFilePath() + "/" + fileTemp);
}
}
}
} catch (Exception e) {
} finally {
//记得关闭连接
if (ftpClient != null) {
ftpClient.quit();
ftpClient.disconnect();
try {
if (ftpClient.getSession() != null)
ftpClient.getSession().disconnect();
} catch (JSchException e) {
log.error("channel getSession error:", e);
}
}
}
}
/**
* 删除服务器端配变的图片(废弃)
*
* @param
* @return
*/
@RequestMapping(value = "/removeImage", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@ResponseBody public Map removeImage(HttpServletRequest request) {
String filePath = apolloConfig.getFilePath();
//删除数据库返回结果
Map result = new HashMap<>();
//获取请求的参数 jsonStr {"3801....@img1&img2&img3"}
String jsonStr = request.getParameter("jsonStr");
String trId = jsonStr.split("@")[0];
String imgIds = jsonStr.split("@")[1];
Map imgMap = new HashMap<>();
String[] s = imgIds.split("&");
for (String obj : s) {
imgMap.put(obj + ".png", obj);
}
//E文件解析工具类
ChannelSftp ftpClient = null;
try {
//连接远程sftp
ftpClient = JcraftTools.getConnect(apolloConfig.getIp(), apolloConfig.getPort(), apolloConfig.getUsername(),
apolloConfig.getPassword());
log.info("删除服务器指定图片------已连接远程服务器!");
// 删除指定文件下的所有文件
Vector ftpFiles = ftpClient.ls(filePath + trId);
if (ftpFiles != null && ftpFiles.size() > 0) {
for (ChannelSftp.LsEntry lsEntry : ftpFiles) {
//临时e文件名称
String fileTemp = lsEntry.getFilename();
if (fileTemp.contains(".png") || fileTemp.contains(".jpg")) {
if (imgMap.containsKey(fileTemp)) {
ftpClient.rm(filePath + trId + "/" + fileTemp);
log.info("文件已删除:" + filePath + trId + "/" + fileTemp);
}
}
}
}
} catch (Exception e) {
} finally {
//记得关闭连接
if (ftpClient != null) {
ftpClient.quit();
ftpClient.disconnect();
try {
if (ftpClient.getSession() != null)
ftpClient.getSession().disconnect();
} catch (JSchException e) {
log.error("channel getSession error:", e);
}
}
}
return result;
}
/**
* IO流读取图片集合(废弃)
*
* @param
* @return
*/
@RequestMapping(value = "/IoReadImageList/{trid}", method = RequestMethod.GET) @ResponseBody
public List IoReadImageList(@PathVariable String trid) throws Exception {
List imgName = new ArrayList<>();
String ftpPath = apolloConfig.getFilePath();
InputStream is = null;
try {
//连接远程sftp
ftpClient = JcraftTools.getConnect(apolloConfig.getIp(), apolloConfig.getPort(), apolloConfig.getUsername(),
apolloConfig.getPassword());
Vector ftpFiles = ftpClient.ls(ftpPath + trid);
if (ftpFiles != null && ftpFiles.size() > 0) {
for (ChannelSftp.LsEntry lsEntry : ftpFiles) {
//临时e文件名称
String fileTemp = lsEntry.getFilename();
if (fileTemp.contains(".png") || fileTemp.contains(".jpg")) {
String imgIoKey = trid + "_" + fileTemp.split("\\.")[0];
//配变下文件名返回给前台
imgName.add(fileTemp.split("\\.")[0]);
is = ftpClient.get(ftpPath + trid + "/" + fileTemp);
//imgIO.put(imgIoKey, is);
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
is.close();
//记得关闭连接
if (ftpClient != null) {
ftpClient.quit();
ftpClient.disconnect();
try {
if (ftpClient.getSession() != null)
ftpClient.getSession().disconnect();
} catch (JSchException e) {
log.error("channel getSession error:", e);
}
}
}
return imgName;
}
/**
* IO流读取图片 by:long(废弃)
*
* @param
* @return
*/
@RequestMapping(value = "/IoReadImageV1/{trid}/{imgId}", method = RequestMethod.GET) public void IoReadImageV1(
@PathVariable String trid, @PathVariable String imgId, HttpServletResponse response) throws Exception {
ServletOutputStream out = null;
String ftpPath = apolloConfig.getFilePath();
InputStream is = null;
//E文件解析工具类
ChannelSftp ftpClient = null;
try {
//连接远程sftp
ftpClient = JcraftTools.getConnect(apolloConfig.getIp(), apolloConfig.getPort(), apolloConfig.getUsername(),
apolloConfig.getPassword());
log.info("IoReadImage------已连接远程服务器!");
is = ftpClient.get(ftpPath + trid + "/" + imgId + ".png");
response.setContentType("image/png");
out = response.getOutputStream();
//读取文件流
int len = 0;
byte[] buffer = new byte[1024 * 10];
while ((len = is.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
out.close();
is.close();
//记得关闭连接
if (ftpClient != null) {
ftpClient.quit();
ftpClient.disconnect();
try {
if (ftpClient.getSession() != null)
ftpClient.getSession().disconnect();
} catch (JSchException e) {
log.error("channel getSession error:", e);
}
}
}
}
/*
* (废弃)
* */
@RequestMapping(value = "/IoReadImageV2/{trid}/{imgId}", method = RequestMethod.GET) public void IoReadImageV2(
@PathVariable String trid, @PathVariable String imgId, HttpServletResponse response) throws Exception {
ServletOutputStream out = null;
InputStream is = null;
String keyImg = trid + "_" + imgId;
Map mapTemp = new HashMap<>();
/* for (Map.Entry io : imgIO.entrySet()) {
String key = io.getKey();
InputStream value = io.getValue();
mapTemp.put(key, value);
}*/
try {
if (mapTemp.containsKey(keyImg)) {
is = mapTemp.get(keyImg);
response.setContentType("image/png");
out = response.getOutputStream();
//读取文件流
int len = 0;
byte[] buffer = new byte[1024 * 10];
while ((len = is.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.flush();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
out.close();
is.close();
}
}
/*
* 文件批量上传(废弃)
* @param files
* @return
* */
@ResponseBody @RequestMapping("/uploadimgs") public ResponseData defectAddUploadImgs(
@RequestParam("file") MultipartFile[] files, @RequestParam("trId") String trId) throws Exception {
ResponseData responseData = null;
//存放图片 服务器ip 端口 用户名 密码
String hostIp = apolloConfig.getIp();
int portNo = apolloConfig.getPort();
String username = apolloConfig.getUsername();
String password = apolloConfig.getPassword();
//服务器存放图片的路径
String filePath = apolloConfig.getFilePath() + trId;
String fileName = null;
if (files != null) {
//JcraftTools连接远程机器
JcraftTools.getConnect(hostIp, portNo, username, password);
//判断目录是否存在 并创建
boolean flag = JcraftTools.createDir(filePath);
if (flag) {
responseData = new ResponseData("500", "存储配变图片目录创建成功!");
log.info("图片上传配变目录创建成功!目录如下:");
for (MultipartFile multipartFile : files) {
//文件名称
fileName = multipartFile.getOriginalFilename();
//江MultipartFile文件转换为File对象
File newFile = FileUtils.MultipartFileToFile(multipartFile);
//转换成IO流
FileInputStream stream = new FileInputStream(newFile);
//取出files[i],进行你的业务逻辑,上传oss或本地服务器
//文件操作 1 判断文件是否存在 存在不动 不存在新建
log.info("图片上传连接服务器成功!");
//JcraftTools上传文件
JcraftTools.uploadIOFile(filePath, stream, fileName);
log.info("传输图片成功 图片:" + fileName);
}
//JcraftTools关闭远程连接
JcraftTools.close();
responseData = new ResponseData("200", "图片上传成功!");
} else {
responseData = new ResponseData("500", "error:请检查服务器存储文件目录是否正确及目录权限、账号是否正确!");
log.info("图片上传配变目录创建成功!目录如下:");
}
}
return responseData;
}
}
//华为云bos存储接口
package com.nari.osp.upload.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.nari.osp.upload.entity.ApolloConfig;
import com.nari.osp.upload.entity.QueryCondition;
import com.nari.osp.upload.entity.TrBaseEntity;
import com.nari.osp.upload.service.UpImgService;
import com.nari.osp.upload.util.FileReadWriteUtils;
import com.nari.osp.upload.util.HuaweiOBSUtil;
import com.nari.osp.upload.util.ResponseData;
import com.nari.osp.upload.util.ZipUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@SuppressWarnings(value = "all") @Service public class ObsUpImgServiceImpl implements UpImgService {
Log log = LogFactory.getLog(getClass());
@Autowired private ApolloConfig apolloConfig;
//图片流(废弃)
Map imgIO = new HashMap<>();
@Override public JSONObject getTrBaseList(QueryCondition queryParam) {
return null;
}
@Override public TrBaseEntity getTrBase(QueryCondition queryParam) {
return null;
}
@Override public void imgUpload(HttpServletRequest request, HttpServletResponse response, String trId)
throws IOException {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
//获取图片上传的批量列表
Map fileMap = multipartRequest.getFileMap();
for (Map.Entry set : fileMap.entrySet()) {
String result = HuaweiOBSUtil.uploadFile(set.getValue(), trId);
if (result.isEmpty()) {
log.info("文件上传失败;上传返回结果为:" + result);
response.sendError(500, "文件上传失败具体参考后台日志");
}
}
}
@Override public List downloadImage(String trid) {
//获取该配变华为云所有已上传文件名称 和 io流
List imgName = HuaweiOBSUtil.getBucketObjectList(trid);
//获取文件io流
for (String obj : imgName) {
InputStream inputStream = HuaweiOBSUtil.downloadFileIOByUrl(obj);
imgIO.put(obj, inputStream);
}
return imgName;
}
@Override public void IoReadImage(String trid, String imgId, HttpServletResponse response) throws IOException {
String keyObs = trid + "/" + imgId;
ServletOutputStream out = null;
InputStream is = null;
Map mapTemp = new HashMap<>();
for (Map.Entry io : imgIO.entrySet()) {
String key = io.getKey();
InputStream value = io.getValue();
mapTemp.put(key, value);
}
try {
if (mapTemp.containsKey(keyObs)) {
is = mapTemp.get(keyObs);
String fileType = FileReadWriteUtils.judgeFileType(keyObs);
if (!"".equals(fileType) && "png".equals(fileType)) {
response.setContentType("application/x-png");
} else if (!"".equals(fileType) && "jpeg".equals(fileType)) {
response.setContentType("image/jpeg");
} else if (!"".equals(fileType) && "jpg".equals(fileType)) {
response.setContentType("image/jpg");
} else {
response.setContentType("image/gif");
}
out = response.getOutputStream();
//读取文件流
int len = 0;
byte[] buffer = new byte[1024 * 10];
while ((len = is.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.flush();
out.close();
is.close();
//图片取出后就删除imgIO
imgIO.remove(keyObs);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
out.close();
is.close();
}
}
@Override public ResponseData removeImage(String trid, String imgId, HttpServletResponse response) {
ResponseData responseData = null;
boolean delFile = HuaweiOBSUtil.deleteFile(trid + "/" + imgId);
//存在直接删除
if (delFile) {
responseData = new ResponseData("200", "图片删除成功!");
} else {
responseData = new ResponseData("500", "图片删除失败!");
}
return responseData;
}
@Override public void fileDownload(String trId, HttpServletRequest request, HttpServletResponse response)
throws IOException {
//本地配变图片存放路径
String localPath = apolloConfig.getLFilePath() + trId;
//String localPath = "C://Users//zhang102594//Desktop//img//" + trId;
//压缩文件路径
String zipPath = apolloConfig.getZipFilePath() + trId + ".zip";
//String zipPath = "C://Users//zhang102594//Desktop//img//" + trId + ".zip";
//判断文件夹 是否存在 存在删除内容 不存在 mkdir
FileReadWriteUtils.dirIsExistOperate(localPath);
//从华为云下载图片至本地服务器
HuaweiOBSUtil.downloadDirIOByUrl(localPath, trId);
FileOutputStream fileOutputStream = new FileOutputStream(new File(zipPath));
//将文件打包到 压缩包目录
boolean isSuccess = ZipUtils.toZip(localPath, fileOutputStream, true);
//如果生成zip成功
if (isSuccess) {
// 保存在本地磁盘中的文件
File file = new File(zipPath);
BufferedInputStream bis = null;
FileInputStream fileInputStream = null;
try {
response.setHeader("content-type", "application/octet-stream");
//我们将文件以流的方式返回前端,但是流无法保存文件名称,因此我们将问文件名称放响应头中返回到前端,前端就可以获取到下载的文件名称了
//在响应头中设置文件名,通过URLEncoder.encode()进行文件编码防止文件名乱码
response.setHeader("Content-disposition",
"attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
// 设置响应类型
response.setContentType("application/x-download");
// 读取本地的文件
fileInputStream = new FileInputStream(file);
// 根据输入流构造一个输入缓冲流对象
bis = new BufferedInputStream(fileInputStream);
byte[] buffer = new byte[1024];
int i = bis.read(buffer);
// 根据response对象构造一个输出流对象,然后将输入流的对象写入输出流
OutputStream os = response.getOutputStream();
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
bis.close();
}
if (fileInputStream != null) {
fileInputStream.close();
}
}
}
}
}
//服务器存储图片代码
package com.nari.osp.upload.service.impl;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.nari.osp.upload.dao.UpImgDao;
import com.nari.osp.upload.entity.ApolloConfig;
import com.nari.osp.upload.entity.QueryCondition;
import com.nari.osp.upload.entity.TrBaseEntity;
import com.nari.osp.upload.service.UpImgService;
import com.nari.osp.upload.util.FileReadWriteUtils;
import com.nari.osp.upload.util.ResponseData;
import com.nari.osp.upload.util.ZipUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@SuppressWarnings(value = "all")
@Service public class UpImgServiceImp implements UpImgService {
Log log = LogFactory.getLog(getClass());
@Autowired private ApolloConfig apolloConfig;
@Autowired private UpImgDao upImgDao;
//图片流(废弃)
Map imgIO = new HashMap<>();
@Override public JSONObject getTrBaseList(QueryCondition queryParam) {
//最终返回结果
JSONArray result = new JSONArray();
//前台筛选条件是否上传图片
String isUpload = queryParam.getIsUpload();
int page = queryParam.getPage();
int rows = queryParam.getRows();
List trListTemp = new ArrayList<>();
List listImgTemp = new ArrayList();
final CountDownLatch latch = new CountDownLatch(2);
ExecutorService es1 = Executors.newFixedThreadPool(2);
//查询配变台账信息
String whereParam = getWhereCondition(queryParam);
es1.execute(new Runnable() {
@Override public void run() {
JSONArray jsonArray = upImgDao.getTrBaseList(whereParam);
for (Object obj : jsonArray) {
TrBaseEntity trBaseEntity = new TrBaseEntity();
// ORGNAME03,ORGNAME04,ORGNAME05,TRID,TRNAME,SNAME,FNAME,PMS_ID PMSID
JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(obj));
String orgName03 = jsonObject.get("ORGNAME03") != null ? jsonObject.getString("ORGNAME03") : "-";
String orgName04 = jsonObject.get("ORGNAME04") != null ? jsonObject.getString("ORGNAME04") : "-";
String orgName05 = jsonObject.get("ORGNAME05") != null ? jsonObject.getString("ORGNAME05") : "-";
String trId = jsonObject.get("TRID") != null ? jsonObject.getString("TRID") : "-";
String trName = jsonObject.get("TRNAME") != null ? jsonObject.getString("TRNAME") : "-";
String sName = jsonObject.get("SNAME") != null ? jsonObject.getString("SNAME") : "-";
String fName = jsonObject.get("FNAME") != null ? jsonObject.getString("FNAME") : "-";
String pmsId = jsonObject.get("PMSID") != null ? jsonObject.getString("PMSID") : "-";
trBaseEntity.setOrgname03(orgName03);
trBaseEntity.setOrgname04(orgName04);
trBaseEntity.setOrgname05(orgName05);
trBaseEntity.setTrNo(trId);
trBaseEntity.setTrName(trName);
trBaseEntity.setSubName(sName);
trBaseEntity.setLineName(fName);
trBaseEntity.setPmsId(pmsId);
trListTemp.add(trBaseEntity);
}
latch.countDown();
}
});
es1.shutdown();
//第二个子线程执行
ExecutorService es2 = Executors.newSingleThreadExecutor();
es2.execute(new Runnable() {
@Override public void run() {
//获取服务器 已上传的配变目录集
List imgNameList = FileReadWriteUtils.getAllFileName(apolloConfig.getLFilePath());
for (String obj : imgNameList) {
listImgTemp.add(obj);
}
latch.countDown();
}
});
es2.shutdown();
try {
latch.await();
//如果是查询全部
if ("00".equals(isUpload)) {
for (TrBaseEntity trBaseEntity : trListTemp) {
if (listImgTemp.contains(trBaseEntity.getTrNo())) {
trBaseEntity.setIsUpload(true);
} else {
trBaseEntity.setIsUpload(false);
}
result.add(trBaseEntity);
}
}
//判断是否上传图片
if ("1".equals(isUpload)) {
for (TrBaseEntity trBaseEntity : trListTemp) {
if (listImgTemp.contains(trBaseEntity.getTrNo())) {
trBaseEntity.setIsUpload(true);
result.add(trBaseEntity);
} else {
continue;
}
}
}
if ("0".equals(isUpload)) {
for (TrBaseEntity trBaseEntity : trListTemp) {
if (listImgTemp.contains(trBaseEntity.getTrNo())) {
continue;
} else {
trBaseEntity.setIsUpload(false);
result.add(trBaseEntity);
}
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return getresultJson(result, page, rows);
}
@Override public TrBaseEntity getTrBase(QueryCondition queryParam) {
String whereParam = getWhereCondition(queryParam);
JSONArray jsonArray = upImgDao.getTrBase(whereParam);
TrBaseEntity trBaseEntity = new TrBaseEntity();
for (Object obj : jsonArray) {
// ORGNAME03,ORGNAME04,ORGNAME05,TRID,TRNAME,SNAME,FNAME,PMS_ID PMSID
JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(obj));
String orgName03 = jsonObject.get("ORGNAME03") != null ? jsonObject.getString("ORGNAME03") : "-";
String orgName04 = jsonObject.get("ORGNAME04") != null ? jsonObject.getString("ORGNAME04") : "-";
String orgName05 = jsonObject.get("ORGNAME05") != null ? jsonObject.getString("ORGNAME05") : "-";
String trId = jsonObject.get("TRID") != null ? jsonObject.getString("TRID") : "-";
String trName = jsonObject.get("TRNAME") != null ? jsonObject.getString("TRNAME") : "-";
String sName = jsonObject.get("SNAME") != null ? jsonObject.getString("SNAME") : "-";
String fName = jsonObject.get("FNAME") != null ? jsonObject.getString("FNAME") : "-";
String pmsId = jsonObject.get("PMSID") != null ? jsonObject.getString("PMSID") : "-";
trBaseEntity.setOrgname03(orgName03);
trBaseEntity.setOrgname04(orgName04);
trBaseEntity.setOrgname05(orgName05);
trBaseEntity.setTrNo(trId);
trBaseEntity.setTrName(trName);
trBaseEntity.setSubName(sName);
trBaseEntity.setLineName(fName);
trBaseEntity.setPmsId(pmsId);
}
return trBaseEntity;
}
@Override public void imgUpload(HttpServletRequest request, HttpServletResponse response, String trId)
throws IOException {
response.setContentType("text/html;charset=UTF-8");
//本地存放图片的路径
String filePath = apolloConfig.getLFilePath() + trId;
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
Map fileMap = multipartRequest.getFileMap();
MultipartFile multipartFile = null;
for (Map.Entry set : fileMap.entrySet()) {
//判断是否有此配变目录 没有创建
FileReadWriteUtils.dirIsExist(filePath);
multipartFile = set.getValue();// 文件名
String fileName = multipartFile.getOriginalFilename();
File file = new File(filePath + "/" + fileName);
log.info("图片上传配变目录创建成功!目录如下:" + fileName);
multipartFile.transferTo(file);
}
}
@Override public List downloadImage(String trid) {
List imgName = new ArrayList<>();
//本地临时文件 前台代码吧 imgTemp
String localPath = apolloConfig.getLFilePath() + trid;
Map allFilePath = FileReadWriteUtils.getAllFilePath(localPath);
for (Map.Entry map : allFilePath.entrySet()) {
String key = map.getKey();
InputStream value = map.getValue();
imgName.add(key);
imgIO.put(trid + "_" + key, value);
}
return imgName;
}
@Override public void IoReadImage(String trid, String imgId, HttpServletResponse response) throws IOException {
String lFilePath = apolloConfig.getLFilePath();
ServletOutputStream out = null;
InputStream is = null;
String keyImg = trid + "_" + imgId;
Map mapTemp = new HashMap<>();
for (Map.Entry io : imgIO.entrySet()) {
String key = io.getKey();
InputStream value = io.getValue();
mapTemp.put(key, value);
}
try {
if (mapTemp.containsKey(keyImg)) {
is = mapTemp.get(keyImg);
String fileType = FileReadWriteUtils.judgeFileType(lFilePath + trid, imgId);
if (!"".equals(fileType) && "png".equals(fileType)) {
response.setContentType("application/x-png");
} else if (!"".equals(fileType) && "jpeg".equals(fileType)) {
response.setContentType("image/jpeg");
} else if (!"".equals(fileType) && "jpg".equals(fileType)) {
response.setContentType("image/jpg");
} else {
response.setContentType("image/gif");
}
out = response.getOutputStream();
//读取文件流
int len = 0;
byte[] buffer = new byte[1024 * 10];
while ((len = is.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.flush();
out.close();
is.close();
//图片取出后就删除imgIO
imgIO.remove(keyImg);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
out.close();
is.close();
}
}
@Override public ResponseData removeImage(String trid, String imgId, HttpServletResponse response) {
ResponseData responseData = null;
String lFilePath = apolloConfig.getLFilePath() + trid;
//获取文件类型
String fileType = FileReadWriteUtils.judgeFileType(lFilePath, imgId);
//判断文件是否存在
boolean fileIsExist = FileReadWriteUtils.fileIsExist(lFilePath + "/" + imgId + "." + fileType);
//存在直接删除
if (fileIsExist) {
boolean delFile = FileReadWriteUtils.delFile(lFilePath + "/" + imgId + "." + fileType);
//imgIO.remove(trid+"_"+imgId);
if (delFile) {
responseData = new ResponseData("200", "图片删除成功!");
} else {
responseData = new ResponseData("500", "图片删除失败!");
}
} else {
responseData = new ResponseData("500", "图片不存在!");
}
return responseData;
}
@Override public void fileDownload(String trId, HttpServletRequest request, HttpServletResponse response)
throws IOException {
//本地配变图片存放路径
String localPath = apolloConfig.getLFilePath() + trId;
//压缩文件路径
String zipPath = apolloConfig.getZipFilePath() + trId + ".zip";
FileOutputStream fileOutputStream = new FileOutputStream(new File(zipPath));
//将文件打包到 压缩包目录
boolean isSuccess = ZipUtils.toZip(localPath, fileOutputStream, true);
//如果生成zip成功
if (isSuccess) {
// 保存在本地磁盘中的文件
File file = new File(zipPath);
BufferedInputStream bis = null;
FileInputStream fileInputStream = null;
try {
response.setHeader("content-type", "application/octet-stream");
//我们将文件以流的方式返回前端,但是流无法保存文件名称,因此我们将问文件名称放响应头中返回到前端,前端就可以获取到下载的文件名称了
//在响应头中设置文件名,通过URLEncoder.encode()进行文件编码防止文件名乱码
response.setHeader("Content-disposition",
"attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
// 设置响应类型
response.setContentType("application/x-download");
// 读取本地的文件
fileInputStream = new FileInputStream(file);
// 根据输入流构造一个输入缓冲流对象
bis = new BufferedInputStream(fileInputStream);
byte[] buffer = new byte[1024];
int i = bis.read(buffer);
// 根据response对象构造一个输出流对象,然后将输入流的对象写入输出流
OutputStream os = response.getOutputStream();
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
bis.close();
}
if (fileInputStream != null) {
fileInputStream.close();
}
}
}
}
public String getWhereCondition(QueryCondition queryParam) {
String result = "";
String orgId = queryParam.getOrgId();
String funcType = queryParam.getFuncType();
String pmsId = queryParam.getPmsId();
String trName = queryParam.getTrName();
String trNo = queryParam.getTrNo();
if (orgId != null && !"".equals(orgId)) {
if (funcType != null && !"".equals(funcType)) {
if ("02".equals(funcType)) { //省
result += " and t1.orgid02='" + orgId + "'";
}
if ("03".equals(funcType)) { //市
result += " and t1.orgid03='" + orgId + "'";
}
if ("04".equals(funcType)) { //县
result += " and t1.orgid04='" + orgId + "'";
}
if ("05".equals(funcType)) { //供电所
result += " and t1.orgid05='" + orgId + "'";
}
if ("sub".equals(funcType)) { //厂站
result += " and t1.sid='" + orgId + "'";
}
if ("feeder".equals(funcType)) { //线路
result += " and t1.fid='" + orgId + "'";
}
if ("tr".equals(funcType)) { //配变
result += " and t1.trid='" + orgId + "'";
}
}
}
if (pmsId != null && !"".equals(pmsId)) {
result += " and t1.pms_id='" + pmsId + "'";
}
if (trName != null && !"".equals(trName)) {
result += " and t1.trname='" + trName + "'";
}
if (trNo != null && !"".equals(trNo)) {
result += " and t1.trid='" + trNo + "'";
}
return result;
}
/**
* 将JSONArray进行分页转化
*
* @param jar
* @param page
* @param rows
* @return
*/
public static JSONObject getresultJson(JSONArray jar, int page, int rows) {
JSONObject json = new JSONObject();
JSONArray array = new JSONArray();
JSONArray page_jar = new JSONArray();
int pages = jar.size() / rows;
int ys = jar.size() % rows;
if (pages != 0) {
if (ys == 0) {
int index = (page - 1) * rows;
int end = index + rows;
for (int l = index; l < end; l++) {
page_jar.add(jar.getJSONObject(l));
}
} else {
if (page <= pages) {
int index = (page - 1) * rows;
int end = index + rows;
for (int l = index; l < end; l++) {
page_jar.add(jar.getJSONObject(l));
}
} else {
int index = pages * rows;
int end = index + ys;
for (int l = index; l < end; l++) {
page_jar.add(jar.getJSONObject(l));
}
}
}
} else {
for (int l = 0; l < ys; l++) {
page_jar.add(jar.getJSONObject(l));
}
}
for (int k = 0; k < page_jar.size(); k++) {
JSONObject jj = page_jar.getJSONObject(k);
JSONObject jor = new JSONObject();
for (String key : jj.keySet()) {
jor.put(key, jj.getString(key) == null ? "" : jj.getString(key).toString());
}
array.add(jor);
}
json.put("total", jar.size());
json.put("rows", array);
return json;
}
}