首先介紹一下多圖上傳有兩個(gè)好用的框架:
1.uploadify
2.zyupload
我用的是zyupload踪少,因?yàn)樗男Ч谑謾C(jī)端用非常友好,下載地址:http://download.csdn.net/detail/sinat_29662475/9580166
使用步驟如下:
(1)引用
<link rel="stylesheet" href="zyupload/skins/zyupload-1.0.0.min.css " type="text/css">
<script type="text/javascript" src="zyupload/zyupload.basic-1.0.0.min.js"></script>
(2)body里面
<div class="upload_btn" style="display: none;" id="upload"></div>
<div id="zyupload" class="zyupload" style="border: 0px;display:block" ></div>
(3)copy一段script代碼
<script type="text/javascript">
$(function(){
// 初始化插件
$("#zyupload").zyUpload({
width : "100%", // 寬度
height : "100px", // 寬度
itemWidth : "75px", // 文件項(xiàng)的寬度
itemHeight : "75px", // 文件項(xiàng)的高度
url : "http://10.0.21.80:8080/ShanglinApp/servlet/UploadAction", // 上傳文件的路徑
fileType : ["jpg","png","js","exe"],// 上傳文件的類(lèi)型
fileSize : 51200000, // 上傳文件的大小
multiple : true, // 是否可以多個(gè)文件上傳
dragDrop : false, // 是否可以拖動(dòng)上傳文件
tailor : false, // 是否可以裁剪圖片
del : true, // 是否可以刪除文件
finishDel : false, // 是否在上傳文件完成后刪除預(yù)覽
/* 外部獲得的回調(diào)接口 */
onSelect: function(selectFiles, allFiles){ // 選擇文件的回調(diào)方法 selectFile:當(dāng)前選中的文件 allFiles:還沒(méi)上傳的全部文件
console.info("當(dāng)前選擇了以下文件:");
console.info(selectFiles);
},
onDelete: function(file, files){ // 刪除一個(gè)文件的回調(diào)方法 file:當(dāng)前刪除的文件 files:刪除之后的文件
console.info("當(dāng)前刪除了此文件:");
console.info(file.name);
},
onSuccess: function(file, response){ // 文件上傳成功的回調(diào)方法
console.info("此文件上傳成功:");
console.info(file.name);
console.info("此文件上傳到服務(wù)器地址:");
console.info(response);
// setTimeout(show(),2000);
// $("#uploadInf").append("<p>上傳成功顶捷,文件地址是:" + response + "</p>");
},
onFailure: function(file, response){ // 文件上傳失敗的回調(diào)方法
console.info("此文件上傳失敳蹲小:");
console.info(file.name);
alert("上傳文件失敗");
},
onComplete: function(response){ // 上傳完成的回調(diào)方法
console.info("文件上傳完成");
console.info(response);
setTimeout(show(),2000);
}
});
});
function show(){
mui.alert("景點(diǎn)評(píng)論成功喘鸟,點(diǎn)擊確定關(guān)閉","景點(diǎn)評(píng)論","確定",function () {
document.location.href="tab-webview-subpage-about.html";
});
}
</script>
(4)點(diǎn)擊上傳的位置對(duì)id為upload的這個(gè)div調(diào)用click事件就ok了
$("#upload").click();
(5)后臺(tái)代碼
demo里面有一個(gè) UploadAction.java文件,做適當(dāng)修改就可以用了最盅,很方便
package servlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import utils.JdbcUtils;
/**
* Servlet implementation class UploadAction
*/
public class UploadAction extends HttpServlet {
private static final long serialVersionUID = 1L;
//上傳文件的保存路徑
protected String configPath = "upload/widget";
protected String dirTemp = "upload/widget/temp";
protected String dirName = "file";
/**
* @see HttpServlet#HttpServlet()
*/
public UploadAction() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
response.setHeader("Access-Control-Allow-Origin", "*");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
System.out.println("get");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setHeader("Access-Control-Allow-Origin","*");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
// response.setHeader("Access-Control-Allow-Origin", "*");
// request.setCharacterEncoding("UTF-8");
// response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
//文件保存目錄路徑
// String savePath = "E:/";
String savePath = this.getServletContext().getRealPath("/") + configPath;
// 臨時(shí)文件目錄
String tempPath = this.getServletContext().getRealPath("/") + dirTemp;
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
String ymd = sdf.format(new Date());
savePath += "/" + ymd + "/";
//創(chuàng)建文件夾
File dirFile = new File(savePath);
if (!dirFile.exists()) {
dirFile.mkdirs();
}
tempPath += "/" + ymd + "/";
//創(chuàng)建臨時(shí)文件夾
File dirTempFile = new File(tempPath);
if (!dirTempFile.exists()) {
dirTempFile.mkdirs();
}
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(20 * 1024 * 1024); //設(shè)定使用內(nèi)存超過(guò)5M時(shí)突雪,將產(chǎn)生臨時(shí)文件并存儲(chǔ)于臨時(shí)目錄中。
factory.setRepository(new File(tempPath)); //設(shè)定存儲(chǔ)臨時(shí)文件的目錄涡贱。
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
try {
List items = upload.parseRequest(request);
System.out.println("items = " + items);
Iterator itr = items.iterator();
while (itr.hasNext())
{
FileItem item = (FileItem) itr.next();
String fileName = item.getName();
long fileSize = item.getSize();
if (!item.isFormField()) {
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
try{
File uploadedFile = new File(savePath, newFileName);
OutputStream os = new FileOutputStream(uploadedFile);
InputStream is = item.getInputStream();
byte buf[] = new byte[1024];//可以修改 1024 以提高讀取速度
int length = 0;
while( (length = is.read(buf)) > 0 ){
os.write(buf, 0, length);
}
//關(guān)閉流
os.flush();
os.close();
is.close();
out.print(savePath+"/"+newFileName);
String getPath = configPath+"/" + ymd + "http://"+newFileName;
System.out.println("我得到的路徑為:"+getPath);
saveImg(getPath);
}catch(Exception e){
e.printStackTrace();
}
}else {
String filedName = item.getFieldName();
System.out.println("===============");
System.out.println(new String(item.getString().getBytes("iso-8859-1"),"utf-8"));
System.out.println("FieldName:"+filedName);
// 獲得裁剪部分的坐標(biāo)和寬高
System.out.println("String:"+item.getString());
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.flush();
out.close();
}
public void saveImg(String img) throws Exception{
String imgs = "";
Connection conn = JdbcUtils.getConnection();
Statement stmt = conn.createStatement();
String sql = "select * from comment order by id desc limit 1";
ResultSet rs = stmt.executeQuery(sql);
int id = 0;
while(rs!=null&&rs.next()){
id = rs.getInt("id");
String imgGet = rs.getString("imgs");
if(imgGet!=null){
imgs = imgGet+"|"+img;
}else{
imgs = img;
}
}
String sql2 = "update comment set imgs = '"+imgs+"' where id = '"+id+"'";
int executeUpdate = stmt.executeUpdate(sql2);
JdbcUtils.close(conn, stmt, rs);
}
}
效果如下:(上傳過(guò)程中會(huì)有進(jìn)度條咏删,很棒的體驗(yàn))
image.png
image.png