html页面
<img class="startImg" id="imgA" src="<c:url value="/resources/images/2.png" />" onclick="$('#picA').click();"/>
<img class="deleteImg" id="deleteA" src="<c:url value="/resources/images/delete.png"/>" onclick="deleteImg('A')"/>
<input type="file" accept="image/jpeg,image/jpg,image/png" style="display: none;" name="picA" id="picA" onchange="getimgloading('A')"/>
javascript
function deleteImg(id) {
$("#pic"+id).val('');
$("#img"+id).attr("src","<c:url value="/resources/images/2.png" />");
$("#delete"+id).hide();
$("#sImg"+id).val("");
}
function getimgloading(id){
var obj=document.getElementById("pic"+id);
var stuff=obj.value.match(/^(.*)(\.)(.{1,8})$/)[3];
console.log(stuff);
if (stuff != 'jpg' && stuff != 'png' && stuff != 'jpeg') {
alert('文件类型不正确');
return false;
}
//判断图片
var file=document.getElementById("pic"+id).files[0];
var reader=new FileReader();
reader.onload = function ( event ) {
if(!/image\/\w+/.test(file.type)){
alert("文件必须为图片!");
return false;
}
src = event.target.result;
$("#img"+id).attr("src",src);
};
reader.readAsDataURL(file);
$("#delete"+id).show();
}
java
String savePath = FileUtils.fileUpload(picA, FileDirectory.QUESTION_DIR, FileDirectory.QUESTION_FIX);
public static String fileUpload(MultipartFile uploadFile, String configFileDirName, String configFileFixName) {
if (uploadFile != null && !uploadFile.isEmpty()) {
//从配置文件获取图片上传物理根路径
String fileUploadRootPath = Configuration.getConfigurationByName(FilePathConfig.FILE_UPLOAD_ROOT_KEY);
if (fileUploadRootPath == null) {
logger.error("获取文件保存根路径异常。");
return null;
}
if (!fileUploadRootPath.endsWith("/")) {
fileUploadRootPath = fileUploadRootPath + "/";
}
if (!configFileDirName.endsWith("/")) {
configFileDirName = configFileDirName + "/";
}
configFileDirName += new SimpleDateFormat("yyyyMMdd").format(new Date());
//根路径+上传目录=最终路径
String companyAbsolutePath = fileUploadRootPath + configFileDirName;
logger.info("从配置文件获取上传文件路径为[" + companyAbsolutePath + "]");
logger.info("创建文件夹[" + companyAbsolutePath + "]结果为[" + FileUtils.getFolder(companyAbsolutePath) + "]");
//根据上传文件获取文件后缀
String subFix = uploadFile.getOriginalFilename().substring(uploadFile.getOriginalFilename().lastIndexOf(".")).toLowerCase();
//生成文件保存名称为
String fileName = configFileDirName + "/" + configFileFixName + "_" + FileUtils.getFileNameByDateTime() + subFix;//customer.getUsername() + "_" +
//获取文件上传路径
String filePath = fileUploadRootPath + fileName;
logger.info("开始上传并保存文件资料至[" + filePath + "]\r\n");
//开始上传并保存文件资料
try {
uploadFile.transferTo(new File(filePath));
} catch (IOException ex) {
logger.error("上传文件出错!错误原因[" + ex.toString() + "]", ex);
return null;
}
return "/"+fileName;
}
return null;
}