前言:業務須要:附件上傳,須要同時知足瀏覽器上傳,和APP上傳附件,而且瀏覽器端不可以使用form表單提交,由於表單提交沒法直接獲取返回值,除非刷新頁面纔可顯示上傳的附件。因此此處使用ajaxfileupload.js,後臺使用的框架是SSH,因此寫了一個servlet來處理上傳附件。css
ajaxfileupload.js是一個異步上傳文件的jQuery插件html
語法:$.ajaxFileUpload([options])java
options參數說明:web
一、url 上傳處理程序地址。
2,fileElementId 須要上傳的文件域的ID,即<input type="file">的ID。
3,secureuri 是否啓用安全提交,默認爲false。
4,dataType 服務器返回的數據類型。能夠爲xml,script,json,html。若是不填寫,jQuery會自動判斷。
5,success 提交成功後自動執行的處理函數,參數data就是服務器返回的數據。
6,error 提交失敗自動執行的處理函數。
7,data 自定義參數。這個東西比較有用,當有數據是與上傳的圖片相關的時候,這個東西就要用到了。
8, type 當要提交自定義參數時,這個參數要設置成postajax
錯誤提示:算法
1,SyntaxError: missing ; before statement錯誤
若是出現這個錯誤就須要檢查url路徑是否能夠訪問
2,SyntaxError: syntax error錯誤
若是出現這個錯誤就須要檢查處理提交操做的服務器後臺處理程序是否存在語法錯誤
3,SyntaxError: invalid property id錯誤
若是出現這個錯誤就須要檢查文本域屬性ID是否存在
4,SyntaxError: missing } in XML expression錯誤
若是出現這個錯誤就須要檢查文件name是否一致或不存在
sql
代碼部分:express
HTML:apache
<div class="add-file"> <input type="button" value="選擇文件"> <input id="textFile" type="text" disabled="disabled" placeholder="未選擇任何文件"> <input type="file" name="file" id="upfile" multiple="multiple" onchange="showUploadFileName(this,'textFile','fileList');"> <button type="button" onclick="ajaxFileUpload('upfile','1','fileList','textFile')">提交</button> <div class="clear"></div> </div>
JavaScript:json
/** * 上傳附件 * @param fileId 附件上傳input ID * @param sourceType 上傳類型 一、任務附件 二、回覆附件 三、 任務結束附件 * @param fileList 顯示附件列表容器id * @param textFile 顯示選中附件名稱容器id * @returns {Boolean} */ function ajaxFileUpload(fileId,sourceType,fileList,textFile) { var replyId = $("#replyId").val(); if(sourceType != 2){ replyId = ""; } if(replyId == undefined){ replyId=""; } //顯示正在上傳的文件 $("#fileList tr").css("display","");//顯示正在上傳的文件 var taskId = $("#taskId").val(); var userid = $("#userID").val(); var name = $("#userName").val(); var url = "/Upload?taskId="+taskId+"&replyId="+replyId+"&userid="+userid+"&name="+name+"&sourceType="+sourceType+"&isApp=noapp"; if($("#"+fileId).val()!=""){ $.ajaxFileUpload ( { url: url, //用於文件上傳的服務器端請求地址 secureuri: false, //是否須要安全協議,通常設置爲false fileElementId: fileId, //文件上傳域的ID dataType: 'json', //返回值類型 通常設置爲json success: function (data, status) //服務器成功響應處理函數 { if(status=="success" && data.message=="success"){ //alert("上傳成功"); $("#"+fileList).empty(); for(var i=0;i<data.list.length;i++){ var html='<tr id="'+data.list[i].annexId+'">'+ '<td style="color: #84bf69;"><i class="jindu-cg"></i>成功</td>'+ '<td>'+data.list[i].fileName+'<span> - '+data.list[i].fileSize/1000+'K</span></td>'+ "<td align='right' onclick=deleteAnnexById('"+data.list[i].annexId+"')><i></i></td>"+ '</tr>'; $("#"+fileList).append(html); } if(sourceType == "3"){//若是是結束任務時上傳的附件,須要局部刷新附件列表 getTaskAnnexList(taskId); } $("#"+textFile).val(""); var file = $("#"+fileId); file.after(file.clone().val("")); file.remove(); }else if(status=="success" && data.message=="failure"){ alert(data.result); } }, error: function (data, status, e)//服務器響應失敗處理函數 { alert(e); } } ) return false; }else{} }
/**
* 顯示選中的文件(一個顯示名字,多個顯示個數)
* @param obj
* @param textFile 顯示選中附件名稱容器id
* @param fileList 顯示附件列表容器id
*/
function showUploadFileName(obj,textFile,fileList){
var t_files = obj.files;
for (var i = 0, len = t_files.length; i < len; i++) {
if(t_files[i].size>10*1024*1024){
alert(t_files[i].name+" 大小超過了10M了,請從新上傳");
return;
}else{
if(t_files.length>1){
$("#"+textFile).val(t_files[0].name+"等"+t_files.length+"個文件");
}else{
$("#"+textFile).val(obj.value);
}
}
var html = '<tr class="" style="display:none">'+
' <td style="color: #007aff;"><i class="jindu-sc"></i>上傳</td>'+
' <td>'+t_files[i].name+'<span> - '+t_files[i].size/1000+'K</span></td>'+
' <td align="right"><i></i></td>'+
'</tr>';
$("#"+fileList).prepend(html);
}
}
java 後臺代碼
web.xml:
<servlet> <servlet-name>Upload</servlet-name> <servlet-class>com.ccidit.features.task.util.upload</servlet-class> </servlet> <servlet-mapping> <servlet-name>Upload</servlet-name> <url-pattern>/Upload</url-pattern> </servlet-mapping>
servlet:
package com.ccidit.features.task.util; import it.sauronsoftware.jave.AudioAttributes; import it.sauronsoftware.jave.Encoder; import it.sauronsoftware.jave.EncoderException; import it.sauronsoftware.jave.EncodingAttributes; import it.sauronsoftware.jave.InputFormatException; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.UUID; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadBase; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.jaudiotagger.audio.AudioFileIO; import org.jaudiotagger.audio.mp3.MP3AudioHeader; import org.jaudiotagger.audio.mp3.MP3File; import com.ccidit.core.common.jdbc.dao.util.JDBCTools; /** * Servlet implementation class FileDemo */ @WebServlet("/FileDemo") public class upload extends HttpServlet { /** * */ private static final long serialVersionUID = 564190060577130813L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String taskId ="";// request.getParameter("taskId"); String replyId ="";// request.getParameter("replyId");//回覆樓層的id Integer userid = 0;// Integer.parseInt(request.getParameter("userid")); String username ="";// request.getParameter("name"); Integer sourceType =0;// Integer.parseInt(request.getParameter("sourceType"));//附件來源類型(一、直屬某一任務二、屬於任務下某條回覆的附件) //獲得上傳文件的保存目錄,將上傳的文件存放於WEB-INF目錄下,不容許外界直接訪問,保證上傳文件的安全 String savePath = "D:/MyInstall/myeclipse2013/tomcat7.0.67/webapps/ueditor/taskAnnex"; //String savePath = "C:/tomcat7.0.67/webapps/ueditor/taskAnnex"; //250 //String path="/home/attachFiles/userpic"; //線上 //上傳時生成的臨時文件保存目錄 String tempPath = this.getServletContext().getRealPath("/WEB-INF/temp"); File tmpFile = new File(tempPath); if (!tmpFile.exists()) { //建立臨時目錄 tmpFile.mkdir(); } File tmpFile1 = new File(savePath); if (!tmpFile1.exists()) { //文件保存路徑 tmpFile1.mkdir(); } //消息提示 String message = ""; try{ //使用Apache文件上傳組件處理文件上傳步驟: //一、建立一個DiskFileItemFactory工廠 DiskFileItemFactory factory = new DiskFileItemFactory(); //設置工廠的緩衝區的大小,當上傳的文件大小超過緩衝區的大小時,就會生成一個臨時文件存放到指定的臨時目錄當中。 factory.setSizeThreshold(1024*100);//設置緩衝區的大小爲100KB,若是不指定,那麼緩衝區的大小默認是10KB //設置上傳時生成的臨時文件的保存目錄 factory.setRepository(tmpFile); //二、建立一個文件上傳解析器 ServletFileUpload upload = new ServletFileUpload(factory); //解決上傳文件名的中文亂碼 upload.setHeaderEncoding("UTF-8"); //三、判斷提交上來的數據是不是上傳表單的數據 if(!ServletFileUpload.isMultipartContent(request)){ //按照傳統方式獲取數據 return; } //設置上傳單個文件的大小的最大值,字節 upload.setFileSizeMax(200*1024*1024); //設置上傳文件總量的最大值,最大值=同時上傳的多個文件的大小的最大值的和 upload.setSizeMax(1024*1024*200); //四、使用ServletFileUpload解析器解析上傳數據,解析結果返回的是一個List<FileItem>集合,每個FileItem對應一個Form表單的輸入項 List<FileItem> list = upload.parseRequest(request); Iterator<FileItem> i = list.iterator(); FileItem item; if(request.getParameter("taskId") != null){ taskId = request.getParameter("taskId"); replyId = request.getParameter("replyId");//回覆樓層的id userid = Integer.parseInt(request.getParameter("userid")); username = request.getParameter("name"); sourceType = Integer.parseInt(request.getParameter("sourceType"));//附件來源類型(一、直屬某一任務二、屬於任務下某條回覆的附件) } while (i.hasNext()) { item = (FileItem) i.next(); //若是fileitem中封裝的是普通輸入項的數據 if(item.isFormField()){ String name = item.getFieldName(); //解決普通輸入項的數據的中文亂碼問題 String value = item.getString("UTF-8"); if(name.equals("taskId")){ taskId=value; } if(name.equals("replyId")){ replyId=value; } if(name.equals("name")){ username=value; } if(name.equals("userid")){ userid=Integer.parseInt(value); } if(name.equals("sourceType")){ sourceType=Integer.parseInt(value); } //System.out.println(name + "=" + value); }else{//若是fileitem中封裝的是上傳文件 //獲得上傳的文件名稱, String filename = item.getName(); //System.out.println(filename); if(filename==null || filename.trim().equals("")){ continue; } //注意:不一樣的瀏覽器提交的文件名是不同的,有些瀏覽器提交上來的文件名是帶有路徑的,如: c:\a\b\1.txt,而有些只是單純的文件名,如:1.txt //處理獲取到的上傳文件的文件名的路徑部分,只保留文件名部分 filename = filename.substring(filename.lastIndexOf("\\")+1); //獲得上傳文件的擴展名 String fileExtName = filename.substring(filename.lastIndexOf(".")+1); //若是須要限制上傳的文件類型,那麼能夠經過文件的擴展名來判斷上傳的文件類型是否合法 //System.out.println("上傳的文件的擴展名是:"+fileExtName); //獲取item中的上傳文件的輸入流 InputStream in = item.getInputStream(); //獲得文件保存的名稱 String saveFilename = makeFileName(filename); //獲得文件的保存目錄 String realSavePath = savePath;//makePath(saveFilename, savePath); //System.out.println(realSavePath); int size = (int) item.getSize(); //建立一個文件輸出流 /* FileOutputStream out = new FileOutputStream(realSavePath + "\\" + saveFilename); //建立一個緩衝區 byte buffer[] = new byte[1024]; //判斷輸入流中的數據是否已經讀完的標識 int len = 0; //循環將輸入流讀入到緩衝區當中,(len=in.read(buffer))>0就表示in裏面還有數據 while((len=in.read(buffer))>0){ //使用FileOutputStream輸出流將緩衝區的數據寫入到指定的目錄(savePath + "\\" + filename)當中 out.write(buffer, 0, len); } //關閉輸入流 in.close(); //關閉輸出流 out.close();*/ //刪除處理文件上傳時生成的臨時文件 //存儲文件 File file = new File(realSavePath); String uploadPath = file.getPath(); File savedFile = new File(realSavePath,saveFilename); item.write(savedFile); item.delete(); if(fileExtName.equals("amr") || fileExtName.equals("mp3")){//音頻文件轉換 String[] a = saveFilename.split("\\."); String fileType = a[a.length-1]; if(fileExtName.equals("amr")){ changeToMp3(realSavePath+"/"+saveFilename,realSavePath+"/"+saveFilename.replace(".amr", ".mp3")); //獲取語音時間長度 File source = new File(realSavePath+"/"+saveFilename.replace(".amr", ".mp3")); MP3File f = (MP3File)AudioFileIO.read(source); MP3AudioHeader audioHeader = (MP3AudioHeader)f.getAudioHeader(); this.addRwAnnex(taskId, "/ueditor/taskAnnex"+"/"+saveFilename.replace(".amr", ".mp3"), filename, audioHeader.getTrackLength(), "mp3", replyId, sourceType,userid,username,saveFilename.replace(".amr", ".mp3")); }else{ //獲取語音時間長度 File source = new File(realSavePath+"/"+saveFilename); MP3File f = (MP3File)AudioFileIO.read(source); MP3AudioHeader audioHeader = (MP3AudioHeader)f.getAudioHeader(); this.addRwAnnex(taskId, "/ueditor/taskAnnex"+"/"+saveFilename, filename, audioHeader.getTrackLength(), fileExtName, replyId, sourceType,userid,username,saveFilename); } }else{ this.addRwAnnex(taskId, "/ueditor/taskAnnex"+"/"+saveFilename, filename, size, fileExtName, replyId, sourceType,userid,username,saveFilename); } message = "文件上傳成功!"; } } }catch (FileUploadBase.FileSizeLimitExceededException e) { e.printStackTrace(); request.setAttribute("message", "單個文件超出最大值!!!"); return; }catch (FileUploadBase.SizeLimitExceededException e) { e.printStackTrace(); request.setAttribute("message", "上傳文件的總的大小超出限制的最大值!!!"); return; }catch (Exception e) { message= "文件上傳失敗!"; e.printStackTrace(); } response.setCharacterEncoding("UTF-8"); response.setContentType("application/json; charset=utf-8"); JSONArray JSONStringlist = getAnnexList(taskId,replyId,sourceType);//獲取附件列表 JSONObject obj = new JSONObject(); obj.put("message", "success"); obj.put("list", JSONStringlist); PrintWriter out1 = null; try { out1 = response.getWriter(); out1.write(obj.toString()); } catch (IOException e) { e.printStackTrace(); } finally { if (out1 != null) { out1.close(); } } } /** * amr 轉mp3 * @param sourcePath * @param targetPath */ public static void changeToMp3(String sourcePath, String targetPath) { File source = new File(sourcePath); File target = new File(targetPath); AudioAttributes audio = new AudioAttributes(); Encoder encoder = new Encoder(); audio.setCodec("libmp3lame"); EncodingAttributes attrs = new EncodingAttributes(); attrs.setFormat("mp3"); attrs.setAudioAttributes(audio); try { encoder.encode(source, target, attrs); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InputFormatException e) { e.printStackTrace(); } catch (EncoderException e) { e.printStackTrace(); } } /** * @Method: makeFileName * @Description: 生成上傳文件的文件名 */ private String makeFileName(String filename){ //爲防止文件覆蓋的現象發生,要爲上傳文件產生一個惟一的文件名 Date currentDate2 = new Date(); SimpleDateFormat df2 = new SimpleDateFormat("yyyyMM"); SimpleDateFormat df3 = new SimpleDateFormat("yyyyMMDDHHMMSS"); String str2 =df2.format(currentDate2); String str3 =df3.format(currentDate2); String[] a = filename.split("\\."); String fileType = a[a.length-1]; String saveFileName =filename.replace("."+fileType, "")+ str3+"."+fileType;//保存的文件名 return saveFileName; //return UUID.randomUUID().toString() + "_" + filename; } /** * 爲防止一個目錄下面出現太多文件,要使用hash算法打散存儲 * @Method: makePath * @Description: * @Anthor: * * @param filename 文件名,要根據文件名生成存儲目錄 * @param savePath 文件存儲路徑 * @return 新的存儲目錄 */ private String makePath(String filename,String savePath){ //獲得文件名的hashCode的值,獲得的就是filename這個字符串對象在內存中的地址 int hashcode = filename.hashCode(); int dir1 = hashcode&0xf; //0--15 int dir2 = (hashcode&0xf0)>>4; //0-15 //構造新的保存目錄 String dir = savePath + "\\" + dir1 + "\\" + dir2; //upload\2\3 upload\3\5 //File既能夠表明文件也能夠表明目錄 File file = new File(dir); //若是目錄不存在 if(!file.exists()){ //建立目錄 file.mkdirs(); } return dir; } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } /** * 添加任務附件記錄 */ public void addRwAnnex(String taskId,String fileDownloadUrl,String fileName,double fileSize,String fileType,String replyId,Integer sourceType,Integer userid,String name,String saveFileName){ String uid = UUID.randomUUID().toString(); String id = uid.replaceAll("-",""); Date date=new Date(); DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm"); String time=format.format(date); String sql = "insert into rw_annex values('"+id+"','"+taskId+"','"+time+"',"+fileSize+",'"+fileType+"','"+fileName+"',"+userid+",'"+name+"','"+fileDownloadUrl+"','"+replyId+"','"+sourceType+"','"+saveFileName+"')"; Statement stmt = null; ResultSet rs = null; Connection conn = JDBCTools.getConnection(); try { stmt = conn.createStatement(); int a = stmt.executeUpdate(sql); }catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ JDBCTools.commit(conn); JDBCTools.release(conn, stmt, rs); } } /** * 獲取附件記錄 */ public JSONArray getAnnexList(String taskId,String replyId,Integer sourceType){ String list=""; String sql = "select * from rw_annex where taskId = '"+taskId+"' and replyId = '"+replyId+"' and sourceType = '"+sourceType+"'order by uploadTime desc"; Statement stmt = null; ResultSet rs = null; Connection conn = JDBCTools.getConnection(); JSONArray array = new JSONArray(); try { stmt = conn.createStatement(); rs = stmt.executeQuery(sql); while(rs.next()){ JSONObject obj = new JSONObject(); obj.put("annexId", rs.getString("annexId")); obj.put("taskId", rs.getString("taskId")); obj.put("uploadTime", rs.getString("uploadTime")); obj.put("fileSize", rs.getString("fileSize")); obj.put("fileType", rs.getString("fileType")); obj.put("fileName", rs.getString("fileName")); obj.put("uploadPeopleId", rs.getString("uploadPeopleId")); obj.put("uploadPeopleName", rs.getString("uploadPeopleName")); obj.put("fileDownloadUrl", rs.getString("fileDownloadUrl")); obj.put("replyId", rs.getString("replyId")); obj.put("sourceType", rs.getString("sourceType")); obj.put("saveFileName", rs.getString("saveFileName")); array.put(obj); } //list = array; }catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ JDBCTools.commit(conn); JDBCTools.release(conn, stmt, rs); } return array; } }
成果展現:
java IO 流下載代碼:
web.xml:
<servlet> <servlet-name>DownLoad</servlet-name> <servlet-class>com.DownLoad</servlet-class> </servlet> <servlet-mapping> <servlet-name>DownLoad</servlet-name> <url-pattern>/DownLoad</url-pattern> </servlet-mapping>
後臺servlet:
package com; import java.io.FileInputStream; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class DownLoad extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { FileInputStream fileInputStream = null; ServletOutputStream servletOutputStream = null; // C:\Windows\System32\drivers\etc String filePath = "C:\\Windows\\System32\\drivers\\etc\\HOSTS"; String fileName = "HOSTS"; try { response.setContentType("application/x-msdownload;"); response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("GBK"), "GBK")); // 將本地文件裝載到內存 fileInputStream = new FileInputStream(filePath); // 實例化輸出流 servletOutputStream = response.getOutputStream(); byte[] buff = new byte[2048]; int bytesRead; // 每次嘗試讀取buff.length長字節,直到讀完、bytesRead爲-1 while ((bytesRead = fileInputStream.read(buff, 0, buff.length)) != -1) { // 每次寫bytesRead長字節 servletOutputStream.write(buff, 0, bytesRead); } // 刷新緩衝區 servletOutputStream.flush(); } catch (IOException e) { } finally { if (fileInputStream != null) { try { fileInputStream.close(); } catch (IOException e) { } } if (servletOutputStream != null) { try { servletOutputStream.close(); } catch (IOException e) { } } } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } public void init() throws ServletException { // Put your code here } }
html部分:
<a href="<%=request.getContextPath() %>/DownLoad">下載</a>
效果:
最後補充 ajaxfileupload.js 連接:http://pan.baidu.com/s/1miIaVGW 密碼:tg5v