//文件上传相关代码
@RequestMapping(value = "/testUploadFileTwo")
@ResponseBody
public String upload( HttpServletRequest Request,@RequestParam MultipartFile file1) {
if (file1.isEmpty()) {
return "文件为空";
}
//允许上传的文件类型
// String fileType = "mp3,mp4,video,rmvb,pdf,txt,xml,doc,gif,png,bmp,jpeg";
//允许上传的文件最大大小(100M,单位为byte)
// int maxSize = 1024*1024*100;
// 获取文件名
String fileName = file1.getOriginalFilename();
//获取上传文件大小
String size = FormetFileSize(file1.getSize());
// 获取文件的后缀名
// String suffixName = fileName.substring(fileName.lastIndexOf("."));
// 文件上传后的路径
String filePath = "E://testNew//";
// 将base64String转为文件转为的路径
String fileNewPath = "E://testNew64//"+fileName;
// 解决中文问题,liunx下中文路径,图片显示问题
// fileName = UUID.randomUUID() + suffixName;
filePath = filePath + fileName;
File dest = new File(filePath);
// 检测是否存在目录
if (!dest.getParentFile().exists())
{
dest.getParentFile().mkdirs();
}
try
{
file1.transferTo(dest);
//將指定路径的文件转为base64字符串
String base64String = MainController.file2Str(filePath);
//将指定的base64字符串文件转为文件
MainController.str2File(base64String, fileNewPath);
return "上传成功";
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "上传失败";
}
/**
* 将文件转化为字节数组字符串,并对其进行Base64编码处理
* @param file
* @return
*/
public static String file2Str(String file){
InputStream in = null;
byte[] data = null;
//读取文件字节数组
try{
in = new FileInputStream(file);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
return new String(Base64.encodeBase64(data));
}
/**
* Base64解码
* @param fileStr 将要转码的字符串
* @param filePath 生成的新路径
* @return
*/
public static boolean str2File(String fileStr,String filePath){
if (fileStr == null) //文件数据为空
return false;
try {
byte[] b = Base64.decodeBase64(fileStr);
for(int i=0;i<b.length;++i){
if(b[i]<0){//调整异常数据
b[i]+=256;
}
}
// 检测是否存在目录,不存在新建文件
File dest = new File(filePath);
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
//生成文件,并保存在服务器硬盘上的文件中
OutputStream out = new FileOutputStream(dest);
out.write(b);
out.flush();
out.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 转换文件大小
* @param fileS
* @return
*/
public String FormetFileSize(long fileS) {
DecimalFormat df = new DecimalFormat("#.00");
String fileSizeString = "";
if (fileS < 1024) {
fileSizeString = df.format((double) fileS) + "B";
} else if (fileS < 1048576) {
fileSizeString = df.format((double) fileS / 1024) + "K";
} else if (fileS < 1073741824) {
fileSizeString = df.format((double) fileS / 1048576) + "M";
} else {
fileSizeString = df.format((double) fileS / 1073741824) +"G";
}
return fileSizeString;
}