1.引入上传js
<script type="text/javascript" src="/js/lib/ajaxfileupload.js"></script>
2.html内容
<input type="file" id="file" name="file" class="file" style="opacity: 0;widht:100px;height:100px" accept="image/*" onchange ="uploadFile(this,'file');">
<input type="hidden" id="save_img" value=""/>
3.后台Java
//获取配置文件中的根目录
public static String getFolder() {
if ("\\".equals(System.getProperties().getProperty("file.separator"))) {
// windows操作系统
String dir = ConfigUtil.getInstance().getProperty("dir.window");
return dir;
} else {
// Linux/Unix操作系统
String dir = ConfigUtil.getInstance().getProperty("dir.linux");
return dir;
}
}
//创建目录
public static void createDirectory(String directory) {
try {
File f = new File(directory);
if (!f.isDirectory()) {
f.mkdirs();
}
} catch (Exception e) {
e.printStackTrace();
}
}
//上传图片
public static String uploadFileAndCallback(MultipartFile file, Integer isThumbnails) {
try {
String filename = file.getOriginalFilename();
String extName=".jpg";
if(filename.indexOf(".")>-1){
extName = filename.substring(filename.lastIndexOf(".")).toLowerCase();
}
long ctime = System.currentTimeMillis();
String lastFileName = ctime + extName;
String tnLastFileNmae = ctime + "_tn" + extName;
// String lastFileName = UUID.randomUUID().toString() + extName;
// 绝对路径
String absPath = FileUtil.getFolder();
// 相对路径路径
String relPath = ConfigUtil.getInstance().getProperty("dir.file")
+ DateUtil.dateToStr(new Date(), "yyyyMMdd/");
// 判断目录是否存在,不存在创建
FileUtil.createDirectory(absPath + relPath);
log.info("file===" + file.getContentType());
// 下载文件
byte[] bytes = commpressPicCycle(file.getBytes(), 500, 0.8);
FileCopyUtils.copy(bytes, new File(absPath + relPath + lastFileName));
log.info("file===" + absPath + relPath + tnLastFileNmae);
if(isThumbnails!=null && isThumbnails>0){
// 生产缩略图
Thumbnails.of(new File(absPath + relPath + lastFileName)).scale(0.3f).toFile(absPath + relPath + tnLastFileNmae);
log.info("file===" + absPath + relPath + tnLastFileNmae);
return relPath + tnLastFileNmae;
}
return relPath + lastFileName;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
// 压缩图片
private static byte[] commpressPicCycle(byte[] bytes, long desFileSize, double accuracy) throws IOException {
// File srcFileJPG = new File(desPath);
long srcFileSizeJPG = bytes.length;
// 判断大小,如果小于500kb,不压缩;如果大于等于500kb,压缩
if (srcFileSizeJPG <= desFileSize * 1024) {
return bytes;
}
// 计算宽高
BufferedImage bim = ImageIO.read(new ByteArrayInputStream(bytes));
int srcWdith = bim.getWidth();
int srcHeigth = bim.getHeight();
int desWidth = new BigDecimal(srcWdith).multiply(
new BigDecimal(accuracy)).intValue();
int desHeight = new BigDecimal(srcHeigth).multiply(
new BigDecimal(accuracy)).intValue();
ByteArrayOutputStream baos = new ByteArrayOutputStream(); //字节输出流(写入到内存)
Thumbnails.of(new ByteArrayInputStream(bytes)).size(desWidth, desHeight).outputQuality(accuracy).toOutputStream(baos);
return commpressPicCycle(baos.toByteArray(), desFileSize, accuracy);
}
4.js内容
function uploadFile(obj, id) {
var _url="/uploadImg.do";
$.ajaxFileUpload({
url : _url,
secureuri : false,// 一般设置为false
fileElementId : id,
data:{fileId:id},
dataType : 'json',// 返回值类型 一般设置为json
success : function(data) // 服务器成功响应处理函数
{
console.log(data);
$(".head_img").attr("src",data.desc);
$("#save_img").val(data.desc);
},
error : function(data)// 服务器响应失败处理函数
{
console.log("服务器异常");
}
});
return false;
}
//获取域名地址
function getContextPath(){
var pathName = document.location.pathname;
var index = pathName.substr(1).indexOf("/");
var result = pathName.substr(0,index+1);
return '';
}