解压文件
/**
* 解压到指定目录
*/
public void unZipFiles(String zipPath, String descDir) throws IOException {
unZipFiles(new File(zipPath), descDir);
}
/**
* 解压文件到指定目录
*/
@SuppressWarnings("rawtypes")
public static void unZipFiles(File zipFile, String descDir) throws IOException {
File pathFile = new File(descDir);
if (!pathFile.exists()) {
pathFile.mkdirs();
}
//解决zip文件中有中文目录或者中文文件
ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"));
for (Enumeration entries = zip.entries(); entries.hasMoreElements(); ) {
ZipEntry entry = (ZipEntry) entries.nextElement();
String zipEntryName = entry.getName();
InputStream in = zip.getInputStream(entry);
String outPath = (descDir + zipEntryName).replaceAll("\\*", "/");
;
//判断路径是否存在,不存在则创建文件路径
File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
if (!file.exists()) {
file.mkdirs();
}
//判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
if (new File(outPath).isDirectory()) {
continue;
}
//输出文件路径信息
log.info(outPath);
OutputStream out = new FileOutputStream(outPath);
byte[] buf1 = new byte[1024];
int len;
while ((len = in.read(buf1)) > 0) {
out.write(buf1, 0, len);
}
in.close();
out.close();
}
log.info("******************解压完毕********************");
}
/**
* 通过excel导入数据
*
* @param request
* @param response
* @return
*/
@RequestMapping(value = "/importExcel", method = RequestMethod.GET)
public Result<?> importExcel() throws Exception {
FileInputStream fileInputStream = null;
try{
// MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
// Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
// for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
// MultipartFile mfile = entity.getValue();// 获取上传文件对象
// byte[] byteArr = mfile.getBytes();
// inputStream = new ByteArrayInputStream(byteArr);
// //上传zip包
// FileUtils.copyInputStreamToFile(inputStream, new File(upLoadPath+"//bindinfo//bindinfoJpg.zip"));
// log.info("绑定信息更新图片 上传zip包成功");
// //解压zip包
// this.unZipFiles(upLoadPath + "//bindinfo//bindinfoJpg.zip", upLoadPath+"//bindinfo//");
// log.info("绑定信息更新图片 解压zip包成功");
//获取解压后的文件夹
File file = new File(upLoadPath + "/bindinfoJpg/");
File[] tempList = file.listFiles();
//对文件夹的图片进行处理
//List<SpcBindInfo> infoList = new ArrayList<>();
for (int i = 0; i < tempList.length; i++) {
if (tempList[i].isFile()) {
File tempFile = tempList[i];
//File转MultipartFile 以便后续处理
fileInputStream = new FileInputStream(tempFile);
MultipartFile multipartFile = new MockMultipartFile(tempFile.getName(), tempFile.getName(), ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
int pos = tempFile.getName().indexOf(".");
if ((pos <= 0) ) {
continue;
}
//获取图片名称 图片名称为bindinfo的id
String id = tempFile.getName().substring(0, pos);
// SpcBindInfo bindInfo = this.spcBindInfoService.getById(id);
// if(bindInfo == null){
// log.info("绑定信息更新图片 绑定信息失败为空 id:"+id);
// continue;
// }
BindImgVo vo = new BindImgVo();
vo.setId(id);
vo.setMultipartFile(multipartFile);
String url = "http://whty.tyjulink.com:82/jeecg-boot/spc/spcBindInfo/updateImg";
Map<String, String> paramMap = new HashMap<>();
paramMap.put("id",id);
String result = HttpUtil.doPostFormData(url,"img",multipartFile,paramMap);
log.info("绑定信息更新图片 id:"+id+" 结果 result:"+result);
}
}
}catch (Exception e){
e.printStackTrace();
return Result.error("文件导入失败!");
}finally {
fileInputStream.close();
}
return Result.ok("文件导入成功!");
}
@RequestMapping(value = "/updateImg", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
@ResponseBody
public Result updateImg(@RequestParam("img") MultipartFile multipartFile,@RequestParam("id") String id){
try{
log.info("绑定信息更新图片 处理图片id:"+id);
SpcBindInfo bindInfo = this.spcBindInfoService.getById(id);
if(bindInfo == null){
log.info("绑定信息更新图片 绑定信息失败为空 id:"+id);
return Result.error("绑定信息更新图片 绑定信息失败为空 id:"+id);
}
//上传图片服务器
FileInfo info = this.fileService.upload(multipartFile);
if(info == null){
log.info("绑定信息更新图片 上传图片失败id:"+id);
return Result.error("绑定信息更新图片 上传图片失败id:"+id);
}
bindInfo.setImgUrl(netWebUrl+"/"+info.getPath());
log.info("绑定信息更新图片 上传图片id:"+id+" 上传成功后的url:"+info.getPath());
this.spcBindInfoService.updateById(bindInfo);
return Result.ok("绑定信息更新图片 上传图片id:"+id+" 上传成功后的url:"+info.getPath());
}catch (Exception e){
log.info("绑定信息更新图片失败!id:"+id);
e.printStackTrace();
return Result.error("绑定信息更新图片失败!id:"+id );
}
}
// 通过post接口去上传文件
package org.jeecg.modules.spc.util;
import net.sf.json.JSONObject;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
public class HttpUtil {
/**
* 以post方式调用第三方接口,以form-data 形式 发送 MultipartFile 文件数据
* @param url post请求url
* @param fileParamName 文件参数名称
* @param multipartFile 文件
*/
public static String doPostFormData(String url, String fileParamName, MultipartFile multipartFile, Map<String, String> paramMap) {
// 创建Http实例
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建HttpPost实例
HttpPost httpPost = new HttpPost(url);
// 请求参数配置
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000)
.setConnectionRequestTimeout(10000).build();
httpPost.setConfig(requestConfig);
try {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(StandardCharsets.UTF_8);
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
String fileName = multipartFile.getOriginalFilename();
// 文件流
builder.addBinaryBody(fileParamName, multipartFile.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);
//表单中其他参数,如果没有其他参数可以注释该部分
for(Map.Entry<String, String> entry: paramMap.entrySet()) {
builder.addPart(entry.getKey(),new StringBody(entry.getValue(), ContentType.create("text/plain", Consts.UTF_8)));
}
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
// 执行提交
HttpResponse response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 返回
String res = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
return res;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (httpClient != null) {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
public static String doPost(String url, JSONObject param) {
HttpPost httpPost = null;
String result = null;
HttpClient client = null;
HttpResponse response = null;
try {
client = new DefaultHttpClient();
httpPost = new HttpPost(url);
if (param != null) {
StringEntity se = new StringEntity(param.toString(), "utf-8");
httpPost.setEntity(se); // post方法中,加入json数据
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("X-Access-Token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2NDI2ODUyODMsInVzZXJuYW1lIjoiYWRtaW4ifQ.Fsd2BU4_l-TWuLyR_JPrpdWdeXi2btAXJF03QBBg8CU");
}
response = client.execute(httpPost);
if (response != null) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity, "utf-8");
}
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (response != null) {
try {
//关闭流
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
if (httpPost != null) {
httpPost.releaseConnection();
}
if (client != null) {
((DefaultHttpClient) client).close();
}
}
return result;
}
public static String doGet(String url) {
HttpGet httpGet = null;
String result = null;
HttpClient client = null;
HttpResponse response = null;
try {
client = new DefaultHttpClient();
httpGet = new HttpGet(url);
httpGet.setHeader("Content-Type", "application/json");
//todo 是否要token
httpGet.setHeader("X-Access-Token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MDM5MzY1NzcsInVzZXJuYW1lIjoiYWRtaW4ifQ.YLw1DXgdiFVBt2UqRfAvM6StGZ6o9ggRC3Xs4-SYPZw");
response = client.execute(httpGet);
if (response != null) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity, "utf-8");
}
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (response != null) {
try {
//关闭流
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
if (httpGet != null) {
httpGet.releaseConnection();
}
if (client != null) {
((DefaultHttpClient) client).close();
}
}
return result;
}
}
//解析txt文件
@Override
public void getBindInfoImg() {
InputStreamReader isr = null;
BufferedReader br = null;
try {
File file = new File("E://图片测试.TXT");
// 将txt格式的数据存入数组
isr = new InputStreamReader(
new FileInputStream(file), "utf-8");
br = new BufferedReader(isr);
// 读取文件的方法
String lineTxt = "";
List<String> list = new ArrayList<>();
while ((lineTxt = br.readLine()) != null) {
if (!(lineTxt.trim().isEmpty())) {
list.add(lineTxt);
}
}
br.close();
String dirName = uploadpath + "/bindinfoJpg/";
for (String s : list) {
// 用于把一个字符串分割成字符串数组
String[] arrStrings = s.split("\\|");
if (arrStrings.length == 2) {
try {
PictureUtil.downloadPicture(arrStrings[1], arrStrings[0], dirName);
}catch (Exception e){
log.info("生成文件报错 id: "+arrStrings[0]);
e.printStackTrace();
continue;
}
}
}
log.info("结束生成压缩文件-----------> ");
} catch (Exception e) {
log.info("获取绑定信息文件失败 ");
e.printStackTrace();
}finally {
}
}