本文分為兩大方面進行講解:
一、java實現動態上傳多個文件
二、解決文件重命名問題java
供大家參考,具體內容如下
1、動態上傳多個文件
遍歷所有要上傳的文件
2、解決文件的重名的問題
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(102410,new File("d:/a"));
ServletFileUpload up = new ServletFileUpload(disk);
try{
List list = up.parseRequest(request);
//只接收圖片.jpg-iamge/jpege.,bmp/imge/bmp,png,
List imgs = new ArrayList();
for(FileItem file :list){
if(file.getContentType().contains("image/")){
String fileName = file.getName();
fileName = fileName.substring(fileName.lastIndexOf("")+1); //獲取擴展
String extName = fileName.substring(fileName.lastIndexOf("."));//.jpg
//UUID
String uuid = UUID.randomUUID().toString().replace("-", "");
//新名稱
String newName = uuid+extName;//在這里用UUID來生成新的文件夾名字,這樣就不會導致重名
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();
}
}
}
以上實現了java多文件上傳,解決了文件重名問題,希望對大家的學習有所幫助。
