SpringMVC上传文件
springMvc上传文件会为我们提供一个文件类MultipartFile,MultipartFile给我们提供了一个transferTo()方法。
直接上代码,以便大家来围观!
前端代码:
<form class="idCardFrontImgForm" name="idCardFrontImgForm" enctype="multipart/form-data">
<input type="text" name="imgtype" value="idCardFrontImg" hidden="hidden">
<input class="fileType" id="idCardFrontImgFile" type="file" name="file">
</form>
js代码:
$("#idCardFrontImgFile").change(function () {
var fm = new FormData();//这里用FormData获取文件等数据
fm.append('file', document.idCardFrontImgForm.file.files[0]);
fm.append('imgType', document.idCardFrontImgForm.imgtype.value);
fm.append('orderNo', document.getElementById("orderNo").value);
var _this = $(this);
upLoadImg(_this, fm);
});
function upLoadImg(_this, fm) {
var file = _this.val();
var fileSize = _this.get(0).files[0].size;
if (!/\.(gif|jpg|jpeg|bmp|GIF|JPG|BMP|JPEG)$/.test(file)) {
alert("图片类型必须是.gif,jpeg,jpg,bmp中的一种");
_this.val("");
return false;
}
if (fileSize > 1024 * 1024 * 10) {
alert("图片大小不能超过10M!");
_this.val("");
return false;
}
$.ajax(
{
url: '/modifyCardsInfo/uploadImg.json',
type: 'POST',
data: fm,
contentType: false, //禁止设置请求类型
processData: false, //禁止jquery对DAta数据的处理,默认会处理
//禁止的原因是,FormData已经帮我们做了处理
dataType: "json",
success: function (result) {
switch (result.code) {
case "000000":
var ImageUrl = result.data.path;
_this.parent().parent().css("background", "rgba(0,0,0,0.0)");
_this.parent().parent().prev().prev().css("display", "none");
_this.parent().parent().prev().attr('src', ImageUrl);
_this.parent().parent().prev().attr('data-src', ImageUrl);
_this.parent().prev().text("重新上传");
_this.val("");
break;
case "000018":
_this.val("");
alert("提交的材料类型不符!");
break;
default:
_this.val("");
alert("网络超时,请重试或联系客服人员!");
break;
}
},
error: function () {
_this.val("");
alert("网络超时,请重试或联系客服人员!");
}
}
);
}
后端代码:
@RequestMapping("/uploadImg.json")
@ResponseBody
public String uploadImg(MultipartFile file, String imgType, String orderNo,
ModelMap modelMap, HttpServletRequest request, HttpServletResponse response) {
HashMap<String, Object> result = new HashMap<>();
//获取文件全名
String fileName = file.getOriginalFilename();
//根据年月日创建多级文件夹
Calendar date = Calendar.getInstance();
SimpleDateFormat yearsFormat = new SimpleDateFormat("yyyy");
SimpleDateFormat monthsFormat = new SimpleDateFormat("MM");
SimpleDateFormat dayFormat = new SimpleDateFormat("dd");
SimpleDateFormat hourFormat = new SimpleDateFormat("HH");
SimpleDateFormat minuteFormat = new SimpleDateFormat("mm");
SimpleDateFormat secondFormat = new SimpleDateFormat("ss");
String years = yearsFormat.format(date.getTime());
String months = monthsFormat.format(date.getTime());
String days = dayFormat.format(date.getTime());
String hours = hourFormat.format(date.getTime());
String minutes = minuteFormat.format(date.getTime());
String seconds = secondFormat.format(date.getTime());
//给文件根据类型重命名
String newFileName = imgType + "_" + hours + minutes + seconds + fileName.substring(fileName.lastIndexOf("."));
//设置存放文件的路径
String extendPath = years + "-" + months + "-" + days + "/" + orderNo.substring(8,14)+orderNo.substring(orderNo.length()-6,orderNo.length()) + "/";
String path = filePath + extendPath;
try {
File newFiles = new File(path);
if (!newFiles.exists()) {
newFiles.mkdirs();
}
if (newFiles.isDirectory()) {
File[] fileArray = newFiles.listFiles();
for (File delFile : fileArray) {
String delFileName = delFile.getName();
if (delFileName.contains(imgType)) {
delFile.delete();
}
}
}
//上传文件
String fileSuffix = fileName.substring(fileName.lastIndexOf("."));
if (!isStandardImage(file, fileSuffix.toLowerCase())) { //isStandardImage工具类 通过流判断文件类型是否与后缀名一致
return newErrorResult(BizCode.ParamError);
}
File newUploadFile = new File(path + newFileName);
newUploadFile.setExecutable(Boolean.FALSE); //设置文件权限不可执行
newUploadFile.setReadable(Boolean.TRUE); //设置文件权限可读
newUploadFile.setWritable(Boolean.TRUE); //设置文件权限可写
file.transferTo(newUploadFile); //上传文件
} catch (IOException e) {
logger.error("上传文件异常:"+e);
return newErrorResult(BizCode.NetworkTimeout);
}
String showImage = staticPath+extendPath+newFileName;
result.put("path", showImage);
return newSuccessResult(result);
}
工具类:
自己写的一些工具类,获取文件流,通过十六进制来判断文件的实际类型与文件后缀名是否一致
/**
* 判断文件后缀名与文件类型是否一致
*
* @param file
* @param fileSuffix
* @return
*/
private boolean isStandardImage(MultipartFile file, String fileSuffix) {
try {
String fileHead = getFileContent(file);
if (fileHead == null || fileHead.length() == 0) {
return false;
}
fileHead = fileHead.toUpperCase();
switch (fileSuffix) {
case ".jpg":
if (fileHead.startsWith("FFD8FF")) {
return true;
}
return false;
case ".jpeg":
if (fileHead.startsWith("FFD8FF")) {
return true;
}
return false;
case ".bmp":
if (fileHead.startsWith("424D")) {
return true;
}
return false;
case ".gif":
if (fileHead.startsWith("47494638")) {
return true;
}
return false;
default:
return false;
}
} catch (IOException e) {
return false;
}
}
/**
* 得到文件头
*
* @param file 上传的文件
* @return 文件头
* @throws IOException
*/
private static String getFileContent(MultipartFile file) throws IOException {
byte[] b = new byte[20];
InputStream inputStream = null;
try {
inputStream = file.getInputStream();
inputStream.read(b, 0, 20);
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
throw e;
}
}
}
return bytesToHexString(b);
}
/**
* 将文件头转换成16进制字符串
*
* @param src
* @return
*/
private static String bytesToHexString(byte[] src) {
StringBuilder stringBuilder = new StringBuilder();
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}
}
以上就是SpringMvc上传文件的实现,写的不好大家多提意见,共同进步啊。