图片删除

/**
* 删除霸屏图片
*1.通过请求,获取到路径
* 2.拼接图片的完整路径
33.利用File 判断是否存在这个图片,存在,就删除。
@param dir
* @return
*/
private boolean deleteScreenPic(String relativePath, String imageName, HttpServletRequest httpServletRequest) {
String templateurl = httpServletRequest.getSession().getServletContext().getRealPath(File.separator);
String temp[] = templateurl.split("webapps");
String realPath = temp[0] + relativePath;
File file = new File(realPath + "/" + imageName);
if (file.exists()) {
return file.delete();
}
else {
return true;
}
}

/**
* 上传banner图片
*/
@Transactional
public Map<String, Object> bannerTempateUploadPic(Long key, ImageType imageType, MultipartFile[] file, HttpServletRequest httpServletRequest) throws IllegalStateException, IOException {
Map<String, Object> response = new HashMap<String, Object>();
boolean status = true;
if (file == null) {
status = false;
}
else {
BufferedImage bannerImage = ImageIO.read(file[0].getInputStream());
BufferedImage campaignImage = ImageIO.read(file[0].getInputStream());
BufferedImage detailImage = ImageIO.read(file[0].getInputStream());
BufferedImage shareImage = ImageIO.read(file[0].getInputStream());
if (bannerImage == null || campaignImage == null || detailImage == null || shareImage == null) {
status = false;
}
else {
// 轮播图,这里设置了图片的长和宽
if (imageType == ImageType.DETAIL) {
if (!(bannerImage.getWidth() == 750 && bannerImage.getHeight() == 375)) {
status = false;
response.put("status", status);
throw new IllegalStateException("轮播图的图片宽为750,高为375");
}
}
if (imageType == ImageType.VIDEO) {
if (!(bannerImage.getWidth() == 750 && bannerImage.getHeight() == 375)) {
status = false;
response.put("status", status);
throw new IllegalStateException("轮播图的图片宽为750,高为375");
}
}
// banner图
if (imageType == ImageType.BANNER) {
if (!(campaignImage.getWidth() == 690 && campaignImage.getHeight() == 276)) {
status = false;
response.put("status", status);
throw new IllegalStateException("活动图的图片宽为690,高为276");
}
}
// 分享图
if (imageType == ImageType.SHARE) {
if (!(shareImage.getWidth() == 120 && shareImage.getHeight() == 120)) {
status = false;
response.put("status", status);
throw new IllegalStateException("分享图的图片宽为120,高为120");
}
}
// 根据key查询uuid
Banner uuidString = contentMapper.selectTanKey(key);
// 根据uuid,查询所属的key
List<Long> key1 = contentMapper.selproductItemInfo3(uuidString.getUuidBanner());
// 循环删除uuid下的key 图片
for (Long uuid : key1) {
String filename = updateImageBanner(uuid, imageType, null, Operation.INSERT);
String path = "/res/campaign/banner/";
filename = this.saveImages(file, path, filename, httpServletRequest);
// contentMapper.bannerTemplatePicUpdates(key);
// contentMapper.bannerTemplatePicUpdate(key);
Map<String, Object> maps = new HashMap<String, Object>();
Banner productTemplate = contentMapper.selectBannerInfobyKey(key);
maps.put("uuidBanner", uuidString.getUuidBanner());
if (imageType.toString().equals("DETAIL")) {
maps.put("bannerImage", filename);
}
if (imageType.toString().equals("VIDEO")) {
maps.put("detailImage", filename);
}
if (imageType.toString().equals("BANNER")) {
maps.put("campaignImage", filename);
}
if (imageType.toString().equals("SHARE")) {
maps.put("shareImage", filename);
}
if (imageType.toString().equals("VIED")) {
maps.put("videoLink", filename);
}
if (contentMapper.updatrImpage(maps) > 0) {
response.put("status", status);
}
else {
throw new IllegalStateException("修改图片失败");
}
response.put("filename", filename);
}
}
response.put("status", status);
// }
}
return response;
}

/**
* 图片上传编辑
*
* @return
*/
@Transactional
private String updateImageBanner(Long key, ImageType imageType, Integer index, Operation operation) {
String picName = "";
Banner productTemplate = contentMapper.selectBannerInfobyKey(key);
if (productTemplate.getKey() == null) {
throw new IllegalStateException("banner模板key不存在");
}
switch (imageType) {
case DETAIL:
List<String> detailLst = productTemplate.getBannerImage() != null ? new ArrayList<>(Arrays.asList(productTemplate.getBannerImage().split(","))) : new ArrayList<>();
picName = "banner_" + RandomStringUtils.randomAlphanumeric(8);
if (operation == Operation.INSERT) {
detailLst.add(picName);
}
else if (operation == Operation.UPDATE) {
detailLst.set(index, picName);
}
else if (operation == Operation.DELETE) {
detailLst.remove(index.intValue());
}
String[] result1 = new String[detailLst.size()];
productTemplate.setBannerImage(StringUtils.join(detailLst.size() == 0 ? null : detailLst.toArray(result1), ","));
break;
case BANNER:
List<String> bannerLst = productTemplate.getCampaignImage() != null ? new ArrayList<>(Arrays.asList(productTemplate.getCampaignImage().split(","))) : new ArrayList<>();
picName = "campaign_" + RandomStringUtils.randomAlphanumeric(8);
if (operation == Operation.INSERT) {
bannerLst.add(picName);
}
else if (operation == Operation.UPDATE) {
bannerLst.set(index, picName);
}
else if (operation == Operation.DELETE) {
bannerLst.remove(index.intValue());
}
String[] result2 = new String[bannerLst.size()];
productTemplate.setCampaignImage(StringUtils.join(bannerLst.size() == 0 ? null : bannerLst.toArray(result2), ","));
break;
case SHARE:
List<String> videoLst = productTemplate.getShareImage() != null ? new ArrayList<>(Arrays.asList(productTemplate.getShareImage().split(","))) : new ArrayList<>();
picName = "share_" + RandomStringUtils.randomAlphanumeric(8);
if (operation == Operation.INSERT) {
videoLst.add(picName);
}
else if (operation == Operation.UPDATE) {
videoLst.set(index, picName);
}
else if (operation == Operation.DELETE) {
videoLst.remove(index.intValue());
}
String[] result3 = new String[videoLst.size()];
productTemplate.setShareImage(StringUtils.join(videoLst.size() == 0 ? null : videoLst.toArray(result3), ","));
break;
case VIDEO:
List<String> videoLst1 = productTemplate.getDetailImage() != null ? new ArrayList<>(Arrays.asList(productTemplate.getDetailImage().split(","))) : new ArrayList<>();
picName = "detail_" + RandomStringUtils.randomAlphanumeric(8);
if (operation == Operation.INSERT) {
videoLst1.add(picName);
}
else if (operation == Operation.UPDATE) {
videoLst1.set(index, picName);
}
else if (operation == Operation.DELETE) {
videoLst1.remove(index.intValue());
}
String[] result4 = new String[videoLst1.size()];
productTemplate.setDetailImage(StringUtils.join(videoLst1.size() == 0 ? null : videoLst1.toArray(result4), ","));
break;
case VIED:
List<String> detailLst7 = productTemplate.getVideoLink() != null ? new ArrayList<>(Arrays.asList(productTemplate.getVideoLink().split(","))) : new ArrayList<>();
picName = "vied_" + RandomStringUtils.randomAlphanumeric(8);
if (operation == Operation.INSERT) {
detailLst7.add(picName);
}
else if (operation == Operation.UPDATE) {
detailLst7.set(index, picName);
}
else if (operation == Operation.DELETE) {
detailLst7.remove(index.intValue());
}
String[] result7 = new String[detailLst7.size()];
productTemplate.setVideoLink(StringUtils.join(detailLst7.size() == 0 ? null : detailLst7.toArray(result7), ","));
break;
default:
break;
}
contentMapper.bannerTemplatePicUpdate(productTemplate);
return picName;
/**
* 上传图片的http请求调用
*
* @param params
* @return
*/
@SuppressWarnings({ "unlikely-arg-type", "unused" })
public String saveImages(MultipartFile[] file, String path, String filename, HttpServletRequest request) {
log.getLogger("content_s").info("saveImages-start({})", file, path, filename, request);
String requestParams = null;
Map<String, String> requestMap = new HashMap<>();
Map<String, Object> resultMap = new HashMap<>();
///这里是内部封装的图片上传的接口。
///
String requestUrl = utilService.getHKCDomain() + "internal/cos/uploadImage.ctrl";
try {
if (file.equals("") || file.length <= 0) {
throw new IllegalStateException("上传文件为空,上传失败~");
}
else {
// 循环获取file数组中得文件
for (int i = 0; i < file.length; i++) {
// 组装请求
ObjectMapper mapper = new ObjectMapper();
// 文件名
// String filename = files[i].getOriginalFilename();
HttpPost httpPost = new HttpPost(requestUrl);
// 构建MultipartEntityBuilder参数
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(java.nio.charset.Charset.forName("UTF-8"));
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);// 加上此行代码解决返回中文乱码问题
builder.addBinaryBody("file", file[0].getInputStream(), ContentType.MULTIPART_FORM_DATA, filename);// 文件流
// builder.addBinaryBody("file", file[i].getInputStream());// 文件流
builder.addTextBody("path", path);
builder.addTextBody("filename", filename);
// TODO不上传图片的话需要设置请求头,如果上传图片的话,默认的就是from-data格式
// builder.setContentType(ContentType.create("multipart/form-data;
// encoding=utf-8"));
// httpPost.setHeader("Content-Type", "multipart/form-data; encoding=utf-8");
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
HttpClient httpClient = HttpClientBuilder.create().build();
// 发送请求
HttpResponse response = httpClient.execute(httpPost);
HttpEntity responseEntity = response.getEntity();
String entityStr = EntityUtils.toString(responseEntity);
JsonNode jsonNode = mapper.readTree(entityStr);
JsonNode responseNode = jsonNode.get("Response");
log.getLogger("content_s").info("addPhone-response req:({}),res:({})", requestMap, entityStr);
ContentResponse pr = mapper.readValue(responseNode.toString(), ContentResponse.class);
// 处理响应
if (pr != null && SUCCESS_CODE.equals(pr.getCode())) {
String name = pr.getData().get("status").toString();
// 获得文件后缀名
filename = name.substring(name.lastIndexOf("/") + 1);
}
else if (pr != null && FIAL_CODE.equals(pr.getCode())) {
throw new IllegalStateException("非法文件类型");
}
else if (pr != null && FIAL_CODE_1.equals(pr.getCode())) {
throw new IllegalStateException("上传图片失败");
}
else if (pr != null && FIAL_CODE_2.equals(pr.getCode())) {
throw new IllegalStateException("文件类型未包含后缀名");
}
else if (pr != null && FIAL_CODE_3.equals(pr.getCode())) {
throw new IllegalStateException("查无此文件");
}
else {
// 无效响应数据
log.getLogger("content_s").error("saveImages-invalidResponse({},{})", requestMap, entityStr);
}
}
}
}
catch (JsonProcessingException e) {
log.getLogger("content_s").error("saveImages-JsonException({},{})", requestMap, e.getMessage());
}
catch (ClientProtocolException e) {
log.getLogger("content_s").error("saveImages-httpClientException({},{})", requestMap, e.getMessage());
}
catch (IOException e) {
log.getLogger("content_s").error("saveImages-IOException({},{})", requestMap, e.getMessage());
}
catch (Exception e) {
log.getLogger("content_s").error("saveImages-Exception({},{})", requestMap, e.getMessage());
}
return filename;
}





}
posted @ 2021-05-10 16:23  夏之  阅读(544)  评论(0编辑  收藏  举报