
<form name="xx" action="<c:url value='/Up3Servlet'/>" method="post" enctype="multjavascript"> function _add(){ var tb = document.getElementById("tb"); //寫(xiě)入一行 var tr = tb.insertRow(); //寫(xiě)入列 var td = tr.insertCell(); //寫(xiě)入數(shù)據(jù) td.innerHTML="File:"; //再聲明一個(gè)新的td var td2 = tr.insertCell(); //寫(xiě)入一個(gè)input td2.innerHTML='<input type="file" name="file"/><button onclick="_del(this);">刪除</button>'; } function _del(btn){ var tr = btn.parentNode.parentNode; //alert(tr.tagName); //獲取tr在table中的下標(biāo) var index = tr.rowIndex; //刪除 var tb = document.getElementById("tb"); tb.deleteRow(index); } function _submit(){ //遍歷所的有文件 var files = document.getElementsByName("file"); if(files.length==0){ alert("沒(méi)有可以上傳的文件"); return false; } for(var i=0;i<files.length;i++){ if(files[i].value==""){ alert("第"+(i+1)+"個(gè)文件不能為空"); return false; } } document.forms['xx'].submit(); } </script></html>
遍歷所有要上傳的文件
解決文件的重名的問(wèn)題
package cn.hx.servlet;import java.io.File;import java.io.IOException;import java.io.PRintWriter;import java.util.ArrayList;import java.util.List;import java.util.UUID;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.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;import org.apache.commons.io.FileUtils;public class UpImgServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String path = getServletContext().getRealPath("/up"); DiskFileItemFactory disk = new DiskFileItemFactory(1024*10,new File("d:/a")); ServletFileUpload up = new ServletFileUpload(disk); try{ List<FileItem> list = up.parseRequest(request); //只接收?qǐng)D片*.jpg-iamge/jpege.,bmp/imge/bmp,png, List<String> imgs = new ArrayList<String>(); for(FileItem file :list){ if(file.getContentType().contains("image/")){ String fileName = file.getName(); fileName = fileName.substring(fileName.lastIndexOf("http://")+1); //獲取擴(kuò)展 String extName = fileName.substring(fileName.lastIndexOf("."));//.jpg //UUID String uuid = UUID.randomUUID().toString().replace("-", ""); //新名稱(chēng) String newName = uuid+extName; //在這里用UUID來(lái)生成新的文件夾名字,這樣就不會(huì)導(dǎo)致重名 FileUtils.copyInputStreamToFile(file.getInputStream(), new File(path+"/"+newName)); //放到list imgs.add(newName); } file.delete(); } request.setAttribute("imgs",imgs); request.getRequestDispatcher("/jsps/imgs.jsp").forward(request, response); }catch(Exception e){ e.printStackTrace(); } }}
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注