結合springmvc,使用ajax上傳base64圖片資料
阿新 • • 發佈:2019-01-05
一、前端:
<input type="file" id="myImage" name="myImage"/>
<script type="text/javascript">
$("#myImage").bind("change",function(){
uploadFile($(this));
});
//通過onChange直接獲取base64資料
q function uploadFile(file){
var f = file.files[0];
var reader = new FileReader();
reader.onload = function (){
var data = e.target.result;
if (data.lastIndexOf('data:base64') != -1) {
data = data.replace('data:base64', 'data:image/jpeg;base64');
} else if (data.lastIndexOf('data:,') != -1) {
data = data.replace('data:,', 'data:image/jpeg;base64,' );
}
if(isCanvasSupported()){
}else{
alert("您的瀏覽器不支援");
}
};
reader.onerror = function(){
console.log("上傳失敗了 ");
}
reader.readAsDataURL(f);
}
//ajax非同步上傳
function ajaxUploadBase64File (base64Data){
var url = window.location.protocol + '//' + window.location.host + "/register/uploadBase64";
$.ajax({
url:url,
type:"post",
data:{base64Data:base64Data},
dataType:"json",
success:function(data){
if(data.success == true){
console.log("上傳成功");
}else{
console.log("上傳失敗");
}
},
error:function(){
console.log("上傳失敗");
}
});
};
//是否支援canvas
function isCanvasSupported(){
var elem = document.createElement('canvas');
return !!(elem.getContext && elem.getContext('2d'));
};
</script>
二、後臺:
@RequestMapping(value="/uploadBase64",method=RequestMethod.POST)
@ResponseBody
public ActionResult<Map<String,String>> base64UpLoad(@RequestParam String base64Data, HttpServletRequest request, HttpServletResponse response){
ActionResult<Map<String,String>> result = new ActionResult<Map<String,String>>();
try{
logger.debug("上傳檔案的資料:"+base64Data);
String dataPrix = "";
String data = "";
logger.debug("對資料進行判斷");
if(base64Data == null || "".equals(base64Data)){
throw new Exception("上傳失敗,上傳圖片資料為空");
}else{
String [] d = base64Data.split("base64,");
if(d != null && d.length == 2){
dataPrix = d[0];
data = d[1];
}else{
throw new Exception("上傳失敗,資料不合法");
}
}
logger.debug("對資料進行解析,獲取檔名和流資料");
String suffix = "";
if("data:image/jpeg;".equalsIgnoreCase(dataPrix)){//data:image/jpeg;base64,base64編碼的jpeg圖片資料
suffix = ".jpg";
} else if("data:image/x-icon;".equalsIgnoreCase(dataPrix)){//data:image/x-icon;base64,base64編碼的icon圖片資料
suffix = ".ico";
} else if("data:image/gif;".equalsIgnoreCase(dataPrix)){//data:image/gif;base64,base64編碼的gif圖片資料
suffix = ".gif";
} else if("data:image/png;".equalsIgnoreCase(dataPrix)){//data:image/png;base64,base64編碼的png圖片資料
suffix = ".png";
}else{
throw new Exception("上傳圖片格式不合法");
}
String tempFileName = getRandomFileName() + suffix;
logger.debug("生成檔名為:"+tempFileName);
//因為BASE64Decoder的jar問題,此處使用spring框架提供的工具包
byte[] bs = Base64Utils.decodeFromString(data);
try{
//使用apache提供的工具類操作流
FileUtils.writeByteArrayToFile(new File(Global.getConfig(UPLOAD_FILE_PAHT), tempFileName), bs);
}catch(Exception ee){
throw new Exception("上傳失敗,寫入檔案失敗,"+ee.getMessage());
}
Map<String,String> map =new HashMap<String,String>();
map.put("tempFileName", tempFileName);
result.setResultMessage("上傳成功");
result.setData(map);
logger.debug("上傳成功");
}catch (Exception e) {
logger.debug("上傳失敗,"+e.getMessage());
result.setSuccess(false);
result.setResultMessage("上傳失敗,"+e.getMessage());
}
return result;
}