boolean isMultipart=ServletFileUpload.isMultipartContent(request);

package com.itheima.tfy.servlet;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.UUID;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


public class UploadServlet1 extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try{

request.setCharacterEncoding("UTF-8");
String storePath=getServletContext().getRealPath("/WEB-INF/upload");
DiskFileItemFactory factory=new DiskFileItemFactory();
//设置临时文件的存放路径
factory.setRepository(new File(getServletContext().getRealPath("/temp")));
ServletFileUpload upload=new ServletFileUpload(factory);
upload.setProgressListener(new ProgressListener() {
//pBytesRead:已读字节数
//pContentLength:文件大小 字节总长度
//pItems: FileItem 文件的索引
public void update(long pBytesRead, long pContentLength, int pItems) {
////XMLHttpServletRequest:js的对象
// //把pBytesRead/pContentLength*100,返回到界面上:XML或JSON(AJAX)


System.out.println("已读"+pBytesRead+",总大小:"+pContentLength+",第几项:"+pItems
+"!!!上传进度="+(pBytesRead/pContentLength*100)+"%");
System.out.println(pBytesRead/pContentLength);
}
});
//设置单个文件的大小
upload.setFileSizeMax(6*1024*1024);
upload.setSizeMax(20*1024*1024);

boolean isMultipart=ServletFileUpload.isMultipartContent(request);
if(isMultipart){
List<FileItem> items=upload.parseRequest(request);
for(FileItem item:items){
if(item.isFormField()){
String fileName=item.getFieldName();
String fileValue=item.getString("UTF-8");
System.out.println(fileName+"="+fileValue);
}else{
String mimeType=item.getContentType();
if(mimeType.startsWith("/image")){
InputStream in=item.getInputStream();//文件内容的输入流
String fileName=item.getName();//上传文件的文件名
if(fileName==null&&"".equals(fileName)){
continue;
}
fileName=fileName.substring(fileName.lastIndexOf("\\")+1);//原来的文件名
fileName=UUID.randomUUID().toString()+"_"+fileName;//UUID.randomUUID()后的文件名
System.out.println(request.getRemoteAddr()+"上传了"+fileName);

String newPath=makeDir(storePath,fileName);
OutputStream out=new FileOutputStream(newPath+"\\"+fileName);

int len=-1;
byte []b=new byte[1024];
while((len=in.read(b))!=-1){
out.write(b, 0, len);
}
in.close();
out.close();
item.delete();//删除临时文件
}
}
}
}
}catch(FileSizeLimitExceededException e){
System.out.println("单个文件不能超过6M");

}catch(FileUploadBase.SizeLimitExceededException e){
System.out.println("总文件大小不能超过6M");

}

catch(Exception e){
e.printStackTrace();
throw new RuntimeException(e);

}


}


private String makeDir(String storePath, String fileName) {
int hashCode=fileName.hashCode();
int dir1=hashCode & 0xf;
int dir2=(hashCode& 0xf0)>>4;
String newPath=storePath+"\\"+dir1+"\\"+dir2;
File file=new File(newPath);
if(!file.exists()){
file.mkdir();
}

return newPath;
}


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {


doGet(request, response);
}


}
{ checkArgument(!dataType.equals(TechDataTypeEnum.NC_DRAWING.getType()), "资料类型错误!"); ContractProject project = projectService.checkProjectStatus(projectId); if (dataType.equals(TechDataTypeEnum.DEEPEN.getType())) { checkArgument(productType != null, "上传深化图纸,缺少产品类型"); if (project.getProjectType().equals(ProjectTypeEnum.MES.getType()) || project.getProjectType().equals(ProjectTypeEnum.BRIDGE.getType())) { checkArgument(ProductTypeEnum.isExist(productType), "建钢产品类型有误"); } } //深化图纸单体id不能为空,其他类型 checkArgument(!dataType.equals(TechDataTypeEnum.DEEPEN.getType()) || monomerId != null, "深化图纸单体id不能为空"); PlanMonomer monomer = null; if (monomerId != null) { monomer = monomerService.getById(monomerId); checkArgument(monomer != null, "导入失败,单体不存在"); } //文件原名称 String originalFilename = multipartFile.getOriginalFilename(); checkArgument(StringUtils.isNotBlank(originalFilename), "压缩文件名称不能为空!"); //获取原文件名后缀 String suffix = FileUtil.getFileExtension(originalFilename); checkArgument("zip".equalsIgnoreCase(suffix), "导入失败,只能上传zip压缩文件"); //构建相对路径 String filePath = getWeldMapFilePath(projectId, monomerId, dataType, productType, project.getProjectType(), null, null); //创建保存绝对路径 D: a/b/1/1/ String absolutePath = configProperties.getFilePath() + filePath; //检验文件目录是否存在,没有则创建 FileUtil.mkdirs(absolutePath); if (StringUtils.isBlank(fileName)) { fileName = originalFilename; } else { String fileSuffix = FileUtil.getFileExtension(fileName); //fileName = ".zip".equalsIgnoreCase(fileSuffix) ? fileName : fileName + ".zip"; fileName = "zip".equalsIgnoreCase(fileSuffix) ? fileName : fileName + ".zip"; } File file = new File(absolutePath + fileName); // try { // //保存压缩文件 absolutePath改为绝对路径 // multipartFile.transferTo(file); // } catch (IOException e) { // e.printStackTrace(); // } List<Long> drawingIds = null; //深化图 if (dataType.equals(TechDataTypeEnum.DEEPEN.getType())) { //解压并获取文件名 List<String> fileNameList = null; try { //解压并获取文件名 fileNameList = unzipFile(file, absolutePath, new HashMap<>()); checkArgument(fileNameList.stream().noneMatch(s -> s.contains(" ")), "文件名不应该包含空格"); } catch (IOException e) { e.printStackTrace(); } checkArgument(CollectionUtils.isNotEmpty(fileNameList), "压缩包解压出现异常!"); drawingIds = new ArrayList<>(fileNameList.size()); if (project.getProjectType().equals(ProjectTypeEnum.MES.getType()) || project.getProjectType().equals(ProjectTypeEnum.BRIDGE.getType())) { DrawingRecognitionRules rules = sysDrawingRecognitionRulesService.getOne(new LambdaQueryWrapper<>()); if (DrawingProductTypeEnum.ARTIFACT.getType().equals(productType)) { checkArgument(rules != null, "图纸识别规则未配置!!!"); } Map<String, Object> map = new HashMap<>(); if (DrawingProductTypeEnum.ARTIFACT.getType().equals(productType)) { try { //获取文件名 List<String> zipNameList = getZipNameList(file); Set<String> nameSet = new HashSet<>(zipNameList); checkArgument(nameSet.size() == zipNameList.size(), "存在重复文件,请审查后重新导入!"); checkArgument(zipNameList.stream().noneMatch(s -> s.contains(" ")), "文件名不应该包含空格"); for (String s : zipNameList) { String serialNumber = s.replaceAll("[.][^.]+$", "").replaceAll(" ", ""); // 获取构件号、构件序列号、图号 map = this.getSerialAndOrder(serialNumber, rules.getType()); // 构件切换图纸识别规则后,删除原来的图纸 this.setWeldMapArtifact(projectId, monomerId, dataType, (String) map.get("serialNumber"), rules.getType(), productType); } } catch (IOException e) { e.printStackTrace(); } } try { for (String name : fileNameList) { // 获取后缀 String fileSuffix = FileUtil.getFileExtension(name); checkArgument("dwg".equalsIgnoreCase(fileSuffix) || "pdf".equalsIgnoreCase(fileSuffix), TechDataTypeEnum.getNameByType(dataType) + "格式不正确!"); String serialNumber = name.replaceAll("[.][^.]+$", "").replaceAll(" ", ""); if (DrawingProductTypeEnum.ARTIFACT.getType().equals(productType)) { // 获取构件号、构件序列号、图号 map = this.getSerialAndOrder(serialNumber, rules.getType()); } // 查询条件 QueryWrapper<TechCappCraftCardProductWeldingMap> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("project_id", projectId) .eq("monomer_id", monomerId) .eq("data_type", dataType) .eq("product_type", productType) .eq("serial_number", DrawingProductTypeEnum.ARTIFACT.getType().equals(productType) ? map.get("serialNumber") : serialNumber); // 构件产品 if (DrawingProductTypeEnum.ARTIFACT.getType().equals(productType)) { // 序列号 if (map.get("number") == null) { queryWrapper.eq("number", 0); } else { queryWrapper.eq("number", map.get("number")); } // 图号 (默认同一单体下的同一构件的图号保持唯一) if (map.get("dwgNum") == null) { queryWrapper.isNull("dwg_num"); } else { queryWrapper.eq("dwg_num", map.get("dwgNum")); } } List<TechCappCraftCardProductWeldingMap> drawings = techCappCraftCardProductWeldingMapMapper.selectList(queryWrapper); Map<String, Object> finalMap = map; TechCappCraftCardProductWeldingMap drawing = drawings.stream().filter(s -> s.getSerialNumber().equals(DrawingProductTypeEnum.ARTIFACT.getType().equals(productType) ? finalMap.get("serialNumber") : serialNumber)).findFirst().orElse(null); // 构件切换图纸识别规则后,删除原来的图纸 this.setWeldMapArtifact(projectId, monomerId, dataType, (String) map.get("serialNumber"), rules.getType(), productType); if (drawing != null) { if (DrawingProductTypeEnum.ARTIFACT.getType().equals(productType) && SysDrawingRecognitionRulesEnums.DRAWING__ARTIFACTS.getType().equals(rules.getType())) { checkArgument(drawing.getDwgNum().equals(map.get("dwgNum")), "导入失败同一单体下图纸的图号默认相同"); } // drawing.setFileName(originalFilename); drawing.setCreateUserId(cacheObjectDTOParam != null ? cacheObjectDTOParam.getCreateUserId() : UserUtil.getCurrentUserId()); drawing.setCreateTime(LocalDateTime.now()); techCappCraftCardProductWeldingMapMapper.updateById(drawing); } if (drawing == null) { drawing = TechCappCraftCardProductWeldingMap.builder() .projectId(projectId) .monomerId(monomerId) .dataType(dataType) .productType(productType) .projectType(project.getProjectType()) .serialNumber(serialNumber) .filePath(filePath) .fileName(name) .createUserId(cacheObjectDTOParam != null ? cacheObjectDTOParam.getCreateUserId() : UserUtil.getCurrentUserId()) .build(); if (DrawingProductTypeEnum.ARTIFACT.getType().equals(productType)) { drawing.setSerialNumber((String) map.get("serialNumber")); drawing.setNumber(map.get("number") == null ? 0 : (Integer) map.get("number")); drawing.setDwgNum((String) map.get("dwgNum")); } techCappCraftCardProductWeldingMapMapper.insert(drawing); } drawingIds.add(drawing.getId()); } } finally { //回收内存 System.gc(); //删除zip文件 file.delete(); } } } } 我该怎么改
最新发布
11-05
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值