頭像上傳外掛
現如今許多web專案都設計到Flash頭像上傳,這套程式碼是我用過許多次的效果特別好,jsp部分可以結合頁面的形式是彈框還是整個頁面都行,只需把這段程式碼加進去,Java部分我的這個例子是springmvc的,大家可以結合自己的框架和命名對程式碼相應的地方進行改動。
1:jsp頁面
<!--頭像-->
<p id="swfContainer">
本元件需要安裝Flash Player後才可使用,請從<a href="https://get.adobe.com/cn/flashplayer/?no_redirect" target="_blank">這裡</a>下載安裝。
</p>
<button type="button" id="upload" style="display:none;margin-top:8px;">swf外定義的上傳按鈕,點選可執行上傳儲存操作</button>
</div>
<script type="text/javascript" src="<%=path%>/resources/js/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="<%=path%>/resources/js/swfobject.js"></script>
<script type="text/javascript" src="<%=path%>/resources/js/fullAvatarEditor.js"></script>
<script type="text/javascript">
swfobject.addDomLoadEvent(function() {
//以下兩行程式碼正式環境下請刪除
var swf = new fullAvatarEditor("<%=path%>/resources/swf/fullAvatarEditor.swf", "<%=path%>/resources/swf/expressInstall.swf", "swfContainer", {
id: 'swf',
upload_url: '<%=path%>/userInfo/upload.htm?userid=${sessionScope.user.userId}&username=${sessionScope.user.userName}', //上傳介面
method: 'post', //傳遞到上傳介面中的查詢引數的提交方式。更改該值時,請注意更改上傳介面中的查詢引數的接收方式
src_upload: 0, //是否上傳原圖片的選項,有以下值:0-不上傳;1-上傳;2-顯示覆選框由使用者選擇
avatar_box_border_width: 0,
avatar_sizes: '100*100|50*50|32*32',
avatar_sizes_desc: '100*100畫素|50*50畫素|32*32畫素'
}, function(msg) {
switch (msg.code)
{
case 1 :
// alert("頁面成功載入了元件!");
break;
case 2 :
// alert("已成功載入圖片到編輯面板。");
document.getElementById("upload").style.display = "inline";
break;
case 3 :
if (msg.type == 0)
{
alert("攝像頭已準備就緒且使用者已允許使用。");
}
else if (msg.type == 1)
{
alert("攝像頭已準備就緒但使用者未允許使用!");
}
else
{
alert("攝像頭被佔用!");
}
break;
case 5 :
if (msg.type == 0)
{
if (msg.content.sourceUrl)
{
alert("頭像上傳成功!");
window.location.replace("${ctx}/userInfo/front_main_2.htm");
//alert("原圖已成功儲存至伺服器,url為:\n" + msg.content.sourceUrl + "\n\n" + "頭像已成功儲存至伺服器,url為:\n" + msg.content.avatarUrls.join("\n\n") + "\n\n傳遞的userid=" + msg.content.userid + "&username=" + msg.content.username);
}
else
{
alert("頭像上傳成功!");
window.location.replace("${ctx}/userInfo/front_main_2.htm");
//alert("頭像已成功儲存至伺服器,url為:\n" + msg.content.avatarUrls.join("\n\n") + "\n\n傳遞的userid=" + msg.content.userid + "&username=" + msg.content.username);
}
}
break;
}
}
);
document.getElementById("upload").onclick = function() {
swf.call("upload");
};
});
</script>
2java後臺
/**
* 頭像上傳
* @param request
* @param response
* @return
* @throws IOException
* @throws FileUploadException
*/
@RequestMapping(value="/upload.htm")
public void upload(HttpServletRequest request, HttpServletResponse response) throws IOException, FileUploadException {
String contentType = request.getContentType();
PrintWriter out = response.getWriter();
if ( contentType.indexOf("multipart/form-data") >= 0 ){
Result result = new Result();
result.avatarUrls = new ArrayList<String>();
result.success = false;
result.msg = "Failure!";
String userid;
String username;
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
FileItemIterator fileItems = upload.getItemIterator(request);
//定義一個變數用以儲存當前頭像的序號
int avatarNumber = 1;
//取伺服器時間+8位隨機碼作為部分檔名,確保檔名無重複。
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssS");
String fileName = simpleDateFormat.format(new Date());
Random random = new Random();
String randomCode = "";
for ( int i = 0; i < 3; i++ ){
randomCode += Integer.toString(random.nextInt(36), 36);
}
fileName = fileName + randomCode;
//基於原圖的初始化引數
String initParams = "";
BufferedInputStream inputStream;
BufferedOutputStream outputStream;
//遍歷表單域
while( fileItems.hasNext()){
FileItemStream fileItem = fileItems.next();
String fieldName = fileItem.getFieldName();
//是否是原始圖片 file 域的名稱(預設的 file 域的名稱是__source,可在外掛配置引數中自定義。引數名:src_field_name)
Boolean isSourcePic = fieldName.equals("__source");
//當前頭像基於原圖的初始化引數(只有上傳原圖時才會傳送該資料,且傳送的方式為POST),用於修改頭像時保證介面的檢視跟儲存頭像時一致,提升使用者體驗度。
//修改頭像時設定預設載入的原圖url為當前原圖url+該引數即可,可直接附加到原圖url中儲存,不影響圖片呈現。
if ( fieldName.equals("__initParams")){
inputStream = new BufferedInputStream(fileItem.openStream());
byte[] bytes = new byte [inputStream.available()];
inputStream.read(bytes);
initParams = new String(bytes, "UTF-8");
inputStream.close();
}else if (isSourcePic || fieldName.startsWith("__avatar")){//如果是原始圖片 file 域的名稱或者以預設的頭像域名稱的部分“__avatar”打頭(預設的頭像域名稱:__avatar1,2,3...,可在外掛配置引數中自定義,引數名:avatar_field_names)
String virtualPath = File.separator+"upload"+File.separator+"img" + avatarNumber + "_" + fileName + ".jpg";//原始圖片(預設的 file 域的名稱是__source,可在外掛配置引數中自定義。引數名:src_field_name)。
String virtualPath1 = "/upload/img" + avatarNumber + "_" + fileName + ".jpg";//原始圖片(預設的 file 域的名稱是__source,可在外掛配置引數中自定義。引數名:src_field_name)。
if( isSourcePic){
String sourceFileName = fileItem.getName(); //檔名,如果是本地或網路圖片為原始檔名、如果是攝像頭拍照則為 *FromWebcam.jpg
String sourceExtendName = sourceFileName.substring(sourceFileName.lastIndexOf('.') + 1);//原始檔案的副檔名(不包含“.”)
result.sourceUrl = virtualPath = String.format(File.separator+"upload"+File.separator+"img_%s.%s", fileName, sourceExtendName);
}else{//頭像圖片(預設的 file 域的名稱:__avatar1,2,3...,可在外掛配置引數中自定義,引數名:avatar_field_names)。
result.avatarUrls.add(virtualPath1);
avatarNumber++;
}
inputStream = new BufferedInputStream(fileItem.openStream());
outputStream = new BufferedOutputStream(new FileOutputStream(request.getRealPath("") + virtualPath));
Streams.copy(inputStream, outputStream, true);
inputStream.close();
outputStream.flush();
outputStream.close();
}else{//註釋① upload_url中傳遞的查詢引數,如果定義的method為post請使用下面的程式碼,否則請刪除或註釋下面的程式碼塊並使用註釋②的程式碼
inputStream = new BufferedInputStream(fileItem.openStream());
byte[] bytes = new byte [inputStream.available()];
inputStream.read(bytes);
inputStream.close();
if (fieldName.equals("userid")){
result.userid = new String(bytes, "UTF-8");
}else if (fieldName.equals("username")){
result.username = new String(bytes, "UTF-8");
}
}
}
//註釋② upload_url中傳遞的查詢引數,如果定義的method為get請使用下面註釋的程式碼
/*
result.userid = request.getParameter("userid");
result.username = request.getParameter("username");
*/
if ( result.sourceUrl != null ){
result.sourceUrl += initParams;
}
result.success = true;
result.msg = "Success!";
List<String> photos = result.avatarUrls;
String photo="";
for(int i=0;i<photos.size();i++){
if(i<photos.size()-1){
photo=photo+photos.get(i)+",";}
else{
photo=photo+photos.get(i);
}
}
UserInfo userInfo=userInfoService.getUserInfo(Integer.parseInt(result.userid ));
userInfo.setPhoto(photo);
userInfoService.user_update(userInfo);
//將修改後的使用者資訊存入session
request.getSession().setAttribute("user", userInfo);
request.getSession().setAttribute("navigationphoto", photos.get(0));
//返回圖片的儲存結果(返回內容為json字串,可自行構造,該處使用fastjson構造)
out.println(JSON.toJSONString(result));
}
}