栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java实现动态上传多个文件并解决文件重名问题

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java实现动态上传多个文件并解决文件重名问题

本文分为两大方面进行讲解:

一、java实现动态上传多个文件

二、解决文件重命名问题java

供大家参考,具体内容如下

1、动态上传多个文件

 
 
 

遍历所有要上传的文件

2、解决文件的重名的问题

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 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多文件上传,解决了文件重名问题,希望对大家的学习有所帮助。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/150442.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号