java 代碼
@RequestMapping(value = "/contributions",method = RequestMethod.POST)
@ResponseBody
public void profile_imgCut(HttpServletResponse response,HttpServletRequest request, Model model,Article article,String info) {
Result result=new Result();
try {
// 存儲目錄
String realDir = request.getSession().getServletContext().getRealPath("/")+IMAGE;
File realDirFile = new File(realDir);
if (!realDirFile.exists()) {
realDirFile.mkdirs();
}
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
//判斷是否有檔案
if (fileMap.size()==0) {
}else{
String filePath="";
String fileName = null;
for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
// 上傳檔案
MultipartFile mf = entity.getValue();
fileName = mf.getOriginalFilename();
String suffixName = FilenameUtils.getExtension(fileName);
//判斷檔案格式
if ("gif".equalsIgnoreCase(suffixName) || "jpg".equalsIgnoreCase(suffixName)
|| "jpeg".equalsIgnoreCase(suffixName) || "bmp".equalsIgnoreCase(suffixName)
|| "png".equalsIgnoreCase(suffixName)) {
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
// 重命名檔案
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String newFileName = df.format(new Date()) + "." + fileExt;
File uploadFile = new File(realDir + "/"+newFileName);
//要存儲在資料庫中的路徑
filePath = IMAGE+"/"+newFileName;
try {
//業務邏輯
result.setSuccess(true);
result.setInfo("投稿成功,請等待管理者稽核");
FileCopyUtils.copy(mf.getBytes(), uploadFile);
} catch (Exception exception) {
System.out.println(exception.getMessage());
result.setSuccess(false);
result.setInfo("未知錯誤,請重新上傳!");
}
} else {
result.setSuccess(false);
result.setInfo("非圖檔格式,請重新上傳!");
}
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
result.setSuccess(false);
result.setInfo("未知錯誤,請重新上傳!");
}
writeJson(response, result);
}
html 代碼
<div class="imgMain" id="imgUploadArea" style="margin-top: 30%;">
<div class="preview">
<img src="${ctxsta}/front/image/noImg.png" id="theirimage">
</div>
<div class="preview" style="width: 250px;margin-left: 10px;">
<img src="" id="myimage">
</div>
<div class="controlArea" style="width: 100px;float: right">
<div class="file-box">
<div id="loading_img" style="display: none;">正在上傳...</div>
<div>
<input id="upload_btn" type="button" class="btn" value='選擇圖檔' />
</div>
<input id="btn1" type="file" accept="image/*,camera" name="filetoupload" capture="camera" style="opacity: 0;"/>
<p>
<input id="deleteImg" type="button" value="删除" class="btn" />
</p>
<p>
<input id="info" type="text" placeholder="請輸入圖檔描述" style="height:24px;border:1px #494949 solid;display: none"/>
</p>
</div>
</div>
</div>
js代碼
這裡使用的是cropper控件
// 圖檔上傳
var $image = $('#theirimage');
$image.cropper({
viewMode: 1,
// preview: '.img-preview', //不同尺寸預覽區
aspectRatio: 1.6/1, // 裁剪比例,NaN-自由選擇區域
autoCropArea: 0.7, // 初始裁剪區域占圖檔比例
crop: function(data) {
var canVas = $image.cropper("getCroppedCanvas", {});
// 将裁剪的圖檔加載到face_image
$('#myimage').attr('src', canVas.toDataURL());
}
});
var fileName; // 選擇上傳的檔案名
$('#btn1').change(function(){
$("#info").show();
var file = this.files[0];
fileName = file.name;
var reader = new FileReader();
// reader回調,重新初始裁剪區
reader.onload = function(){
// 通過 reader.result 來通路生成的 DataURL
var url = reader.result;
// 選擇圖檔後重新初始裁剪區
$image.cropper('reset', true).cropper('replace', url);
};
reader.readAsDataURL(file);
});
上傳ajax
$("#poste").attr("enctype","multipart/form-data");
var type = $image.attr('src').split(';')[0].split(':')[1];
var canVas = $image.cropper("getCroppedCanvas", {});
// 将裁剪的圖檔加載到face_image
$('#myimage').attr('src', canVas.toDataURL());
if (canVas.toBlob) {
canVas.toBlob(function(blob) {
var formData = new FormData();
formData.append("file", blob, fileName);
formData.append("info",$('#info').val());
formData.append("content",ue.getContent());
formData.append("categoryId",$('#categoryId').val());
formData.append("author",$('#author').val());
formData.append("email",$('#email').val());
formData.append("source",$('#source').val());
formData.append("title",$('#title').val());
$.ajax({
type: "POST",
url: ctx+'/front/contributions',
data: formData,
contentType: false, // 必須
processData: false, // 必須
dataType: "json",
success: function(retJson){
if(retJson.success){
layer.msg(retJson.info, {
shade : 0.3,
time : 1500
}, function() {
window.location.href= ctx+'/front/index';
});
}else{
layer.msg(retJson.info, {
shade : 0.3,
time : 1500
});
}
},
error : function() {
}
});
}, type);
}
在這裡 toBlob方法在浏覽器中的相容不好,在谷歌浏覽器中才能用 需要導入一個js檔案
具體參看 https://github.com/blueimp/JavaScript-Canvas-to-Blob
引入即可