有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JavaServlet可以与HTML表单标记一起使用,以允许用户将文件上载到服务器

我想上传一个excel文件。此文件将以重命名而不是文件名保存在特定路径中。该重命名包含名称、当前系统时间和日期。例如上传一个新的。xsl文件它将保存为新的\u 4/14/2014\u 1:57。我试了很多,但还是有问题。我在这里附上了我的片段。你能告诉我哪里出了错吗

 </head>
 <body>
 <h1>welcome to excel upload</h1>
 <form action ="UploadServlet" method ="post" enctype ="multipart/form-data">
 Upload a selected file: <input type="file" name="file" size="50"><br><br>
         <input type="submit"  value="uploadFile">
         <input type="submit"   value="cancel">
  </form>
  </body>
  </html>
    output:welcome to excel upload

    Upload a selected file: 




package com.bala;

import java.awt.List;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.Date;

import javax.servlet.ServletConfig;
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.io.output.*;


public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
 private boolean isMultipart;
   private String filePath;
   private int maxFileSize = 250 * 1024;
   private int maxMemSize = 4 * 1024;
   private File file ;
   String s1 = " ";
   String s2 = " ";
    public void init( ){

         filePath = 
              getServletContext().getInitParameter("file-upload"); 
       }
   public UploadServlet() {}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws                 ServletException, IOException {

isMultipart = ServletFileUpload.isMultipartContent(request);

response.setContentType("text/html");
java.io.PrintWriter out = response.getWriter( );
if( !isMultipart ){
     out.println("<html>");
   out.println("<head>");
   out.println("<title>Servlet upload</title>");  
   out.println("</head>");
   out.println("<body>");
   out.println("<p>No file uploaded</p>"); 
   out.println("</body>");
   out.println("</html>");
   return;
}
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(maxMemSize);
factory.setRepository(new     File("C:/glassfish3/glassfish/domains/domain1/applications/data"));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax( maxFileSize );

try{ 
     // Parse the request to get file items.
     java.util.List<FileItem> fileItems = upload.parseRequest(request);

    // Process the uploaded file items
     Iterator i = fileItems.iterator();

    out.println("<html>");
    out.println("<head>");
    out.println("<title>Servlet upload</title>");  
    out.println("</head>");
    out.println("<body>");
    while ( i.hasNext () ) 
    {
       FileItem fi = (FileItem)i.next();
       if ( !fi.isFormField () )    
       {

           // Get the uploaded file parameters
          String fieldName = fi.getFieldName();
          String fileName = fi.getName();
          String contentType = fi.getContentType();
          boolean isInMemory = fi.isInMemory();
          long sizeInBytes = fi.getSize();
       //* request.setAttribute("UPLOAD_DIRECTORY", file);
         // Date date = new Date();
       //SimpleDateFormat ft = 
                 //new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
        //String s = ft.format(date);
       // String filename = "bala";
        //String  filename1 =  s+ "_" + filename;
       //String fileName1 = file.getFileName();
      // out.println(filename1);
          //Rename the file
         // File oldfile = new File(s1);
        // out.println("old file name.."+oldfile);
        // File newfile = new File(s2);
          //out.println("new file name..."+newfile);
         // if(oldfile.renameTo(newfile)){
              //filename = "bala" + file.separator +filename1;
              // Write the file
          if( fileName.lastIndexOf("\\") >= 0 ){
            file = new File(filePath  + 
                     fileName.substring( fileName.lastIndexOf("\\") ));
           }else{
             file = new File( filePath + 
             fileName.substring(fileName.lastIndexOf("\\")+1)) ;
          }

         fi.write( file);
          out.println("Uploading the file successfully." +"<br>");

          out.println("Uploaded Filename: " + fileName+"<br>");
       }
    }

    out.println("</body>");
    out.println("</html>");
 }catch(Exception ex) {
     System.out.println(ex);
 }
 }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws     ServletException, IOException,java.io.IOException {
 throw new ServletException("GET method used with " +
           getClass( ).getName( )+": POST method required.");
  } 

}

共 (2) 个答案

  1. # 1 楼答案

    在浏览了你代码的注释行之后,我想我明白了你想要做的事情

    Check if that file already excists in the folder, if yes, then rename old one to something and write new on old one.

    如果是这样的话,

    File uploadedFile = new File(fileName);
    if(uploadedFile.exists()){ // We check if there exists an old file
      String timestamp = new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz").format(new Date());
      String backupFileName = "bkp_" + timestamp + fileName;
      uploadedFile.renameTo(new File(backupFileName)); //If there exists , then rename it
    }
    //Now write the new file
    

    我无法检查代码,但你肯定能从中得到灵感

    与您的更新一起

    为什么不干脆

    String timestamp = new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz").format(new Date());   
    String newFileName = fileName + "_" + timestamp;
    File newFile = new File(newFileName);
    //Now write the new file
    //Well, writing the file to disk do depend on several facts. 
    //I guess you are not asking the codes to write the file to disk.
    
  2. # 2 楼答案

    你最好只使用html页面来实现ui目的
    并在背面编写servlet代码

    通过以下链接,它将解决您的问题

    servlets-file-uploading