Java implementation dynamically uploads multiple files and resolves file name problems (GO)

Source: Internet
Author: User
Tags uuid

This article is divided into two major areas to explain:

One, Java implementation dynamically upload multiple files

Second, solve the problem of file renaming Java

For your reference, the specific contents are as follows

1. Uploading multiple files dynamically

<script>

< form name = "xx" action="<c:url value = ‘/Up3Servlet‘ />" method="post" enctype="multipart/form-data">    < table id = "tb" border = "1" >      < tr >        < td >          File:        </ td >        < td >          < input type = "file" name = "file" >          < button onclick = "_del(this);" >删除</ button >        </ td >      </ tr >    </ table >    < br />    < input type = "button" onclick = "_submit();" value = "上传" >    < input onclick = "_add();" type = "button" value = "增加" >    </ form >   </ body >   < script type = "text/javascript" >     function _add(){       var tb = document.getElementById("tb");       //写入一行       var tr = tb.insertRow();       //写入列       var td = tr.insertCell();        //写入数据       td.innerHTML="File:";       //再声明一个新的td       var td2 = tr.insertCell();       //写入一个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中的下标       var index = tr.rowIndex;       //删除       var tb = document.getElementById("tb");       tb.deleteRow(index);     }     function _submit(){       //遍历所的有文件       var files = document.getElementsByName("file");       if(files.length==0){         alert("没有可以上传的文件");         return false;       }       for(var i=0;i< files.length ;i++){         if(files[i].value==""){           alert("第"+(i+1)+"个文件不能为空");           return false;         }       }      document.forms[‘xx‘].submit();     }   </script>

Traverse all the files to be uploaded

2. Solve the problem of duplicate file name

  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);        //只接收图片*.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( "\\" )+ 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();      }       } }The above implementation of the Java multi-file upload, solve the problem of duplicate file name, I hope that everyone's learning has helped.

Java implementation dynamically uploads multiple files and resolves file name problems (GO)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.