这里我讲述的是将文件(压缩包)上传至本地,但是我们真正的需求是将文件上传至指定的服务器,这里我还需要去进一步的研究学习!
需求:前端点击添加按钮,选择一个压缩包,点击上传,此时后端就需要接收这个压缩包,那么我们接收到这个压缩包之后,需要做进一步的处理:
1. 验证上传的压缩包格式是否符合要求;
2. 采用md5的方式验证压缩包的一致性;
3. 解压缩;
4. 拿到文件中的一个xml文件;
5. 解析xml文件;
6. 获取到xml文件中的参数,进行校验;
7. 将xml文件中的数据入库;
8. 再将压缩包传至本地。
9. 返回给前端-上传完毕!
这里附上全部的代码:
commons-lang commons-lang 2.6 commons-io commons-io 2.11.0 org.jdom jdom2
@RestController
@Slf4j
public class UploadFileController {
@PostMapping("upload")
public String upload(MultipartFile file) {
try {
//获取文件名,file.zip
String filename = file.getOriginalFilename();
log.info("文件名:{}", filename);
String filetype = null;
if (StringUtils.isNotEmpty(filename)) {
//.zip
filetype = FileTypeUtils.getFileType(filename);
}
log.info("文件类型:{}", filetype);
//返回md5值
String md5 = Md5Utils.getFileInputStreamMD5String(file.getInputStream());
log.info("校验的值:{}", md5);
//转换为File,是创建一个临时文件,使用过后将临时文件删除。
String time = System.currentTimeMillis() + "_";//当前时间戳
String filename1 = time + "." + filetype;//临时文件名称
File file1 = new File("E:/" + filename1);//临时文件存储位置E:
public class FileTypeUtils
{
public static String getFileType(File file)
{
if (null == file)
{
return StringUtils.EMPTY;
}
return getFileType(file.getName());
}
public static String getFileType(String fileName)
{
int separatorIndex = fileName.lastIndexOf(".");
if (separatorIndex < 0)
{
return "";
}
return fileName.substring(separatorIndex + 1).toLowerCase();
}
public static String getFileExtendName(byte[] photoByte)
{
String strFileExtendName = "JPG";
if ((photoByte[0] == 71) && (photoByte[1] == 73) && (photoByte[2] == 70) && (photoByte[3] == 56)
&& ((photoByte[4] == 55) || (photoByte[4] == 57)) && (photoByte[5] == 97))
{
strFileExtendName = "GIF";
}
else if ((photoByte[6] == 74) && (photoByte[7] == 70) && (photoByte[8] == 73) && (photoByte[9] == 70))
{
strFileExtendName = "JPG";
}
else if ((photoByte[0] == 66) && (photoByte[1] == 77))
{
strFileExtendName = "BMP";
}
else if ((photoByte[1] == 80) && (photoByte[2] == 78) && (photoByte[3] == 71))
{
strFileExtendName = "PNG";
}
return strFileExtendName;
}
}
public class Md5Utils {
public static String getMD5String(String s) {
return DigestUtils.md5Hex(s);
}
public static boolean checkMd5(String md5str1, String md5str2) {
return md5str1.equals(md5str2);
}
public static String getFileMD5String(File file) throws IOException {
InputStream fis;
fis = new FileInputStream(file);
String md5=DigestUtils.md5Hex(fis);
fis.close();
return md5;
}
public static String getFileInputStreamMD5String(InputStream fis) throws IOException {
String md5=DigestUtils.md5Hex(fis);
fis.close();
return md5;
}
}



