web app專案使用uploadifive外掛上傳圖片
阿新 • • 發佈:2019-01-08
做了一個微信公眾號的專案,需要上傳使用者的照片資料。使用了uploadifive.js外掛做的圖片上傳。
具體操作如下:
參考文件:
1.引入相關js
<link rel="stylesheet" href="static/css/uploadifive.css">
<script type="text/javascript" src="static/js/jquery.uploadifive.js"></script>
2.input 標籤
<span class="contM">照片</span>
<input type ="file" id="f_zp" accept="image/*" />
<img class="img"/>
<input type="hidden" name="URL_ZP">
3.上傳的js
$(function(){
$("input[id^='f_']").uploadifive({
//指定swf檔案
'swf': '<%=basePath%>static/js/uploadify.swf',
//後臺處理的頁面
'uploadScript' : '<%=basePath%>uploadImg' ,
//按鈕顯示的文字
'buttonText': '上傳圖片',
//在瀏覽視窗底部的檔案型別下拉選單中顯示的文字
'fileTypeDesc': 'Image Files',
//允許上傳的檔案字尾
'fileTypeExts': '*.gif; *.jpg; *.png',
//傳送給後臺的其他引數通過formData指定
'formData' : {
'timestamp' : '111'
},
//上傳完成時的回撥方法
'onUploadComplete' :function(file,data){
var temp=eval('(' + data + ')').content;
//因js控制元件會自動生成一下子標籤。所以需要向上取父節點,才能得到想要的dom節點。
this[0].parentNode.parentNode.nextElementSibling.src=temp;
$(this[0].parentNode.parentNode).next().next().val(temp);
}
});
})
4.後臺java相關程式碼
1.因為使用的是spring mvc進行的上傳處理。所以需要在spring-mvc.xml中配置MultipartFile Bean .
<!-- 上傳攔截,如最大上傳值及最小上傳值 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" >
<property name="maxUploadSize">
<value>104857600</value>
</property>
<property name="maxInMemorySize">
<value>4096</value>
</property>
<property name="defaultEncoding">
<value>utf-8</value>
</property>
</bean>
2.業務程式碼:
@RequestMapping(value = "/uploadImg")
@ResponseBody
public Result upload(@RequestParam(value = "Filedata", required = false) MultipartFile file, HttpServletRequest request, ModelMap model) {
Result result=null;
String path = request.getSession().getServletContext().getRealPath("uploadFiles");
String fileName = DateUtil.getCurrentTime()+RandomUtils.buildRandom(12)+StringUtils.substring(file.getOriginalFilename(), StringUtils.indexOf(file.getOriginalFilename(),"."));
File targetFile = new File(path, fileName);
if(!targetFile.exists()){
targetFile.mkdirs();
}
try {
//儲存
file.transferTo(targetFile);
result=new Result("成功");
result.setContent(request.getContextPath()+"/uploadFiles/"+fileName);
} catch (Exception e) {
result=new Result("失敗");
e.printStackTrace();
}
//返回的資料格式為:
//{"header":{"status":1},"content":"/XXX/uploadFiles/20170609111534-415672534.png"}
return result;
}