Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/359.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Servlet可以与HTML表单标记一起使用,以允许用户将文件上载到服务器_Java_Servlets - Fatal编程技术网

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

Java Servlet可以与HTML表单标记一起使用,以允许用户将文件上载到服务器,java,servlets,Java,Servlets,我想上传一个excel文件。此文件将以重命名而不是文件名保存在特定路径中。该重命名包含名称、当前系统时间和日期。例如,上传一个新的.xsl文件,它将像新的\u 4/14/2014\u 1:57那样保存。我试了很多,但还是有问题。我在这里附上了我的片段。你能告诉我哪里出了错吗 </head> <body> <h1>welcome to excel upload</h1> <form action ="UploadServlet" met

我想上传一个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.");
  } 

}

欢迎使用excel上传
上载所选文件:

输出:欢迎使用excel上传 上载所选文件: 包com.bala; 导入java.awt.List; 导入java.io.File; 导入java.io.IOException; 导入java.text.simpleDataFormat; 导入java.util.Iterator; 导入java.util.Date; 导入javax.servlet.ServletConfig; 导入javax.servlet.ServletException; 导入javax.servlet.http.HttpServlet; 导入javax.servlet.http.HttpServletRequest; 导入javax.servlet.http.HttpServletResponse; 导入org.apache.commons.fileupload.FileItem; 导入org.apache.commons.fileupload.FileUploadException; 导入org.apache.commons.fileupload.disk.DiskFileItemFactory; 导入org.apache.commons.fileupload.servlet.ServletFileUpload; 导入org.apache.commons.io.output.*; 公共类UploadServlet扩展了HttpServlet{ 私有静态最终长serialVersionUID=1L; 私有布尔是多重的; 私有字符串文件路径; private int maxFileSize=250*1024; 私有整数maxmesize=4*1024; 私有文件; 字符串s1=“”; 字符串s2=“”; 公共void init(){ 文件路径= getServletContext().getInitParameter(“文件上载”); } 公共上载servlet(){} 受保护的void doPost(HttpServletRequest请求、HttpServletResponse响应)引发ServletException、IOException{ isMultipart=ServletFileUpload.isMultipartContent(请求); response.setContentType(“text/html”); java.io.PrintWriter out=response.getWriter(); 如果(!isMultipart){ out.println(“”); out.println(“”); out.println(“Servlet上传”); out.println(“”); out.println(“”); out.println(“没有上传文件”

”; out.println(“”); out.println(“”); 返回; } DiskFileItemFactory=新的DiskFileItemFactory(); factory.setSizeThreshold(maxMemSize); setRepository(新文件(“C:/glassfish3/glassfish/domains/domain1/applications/data”); ServletFileUpload upload=新的ServletFileUpload(工厂); upload.setSizeMax(maxFileSize); 试试{ //解析请求以获取文件项。 java.util.List fileItems=upload.parseRequest(请求); //处理上载的文件项 迭代器i=fileItems.Iterator(); out.println(“”); out.println(“”); out.println(“Servlet上传”); out.println(“”); out.println(“”); 而(i.hasNext()) { FileItem fi=(FileItem)i.next(); 如果(!fi.isFormField()) { //获取上传的文件参数 字符串fieldName=fi.getFieldName(); 字符串文件名=fi.getName(); 字符串contentType=fi.getContentType(); 布尔值isInMemory=fi.isInMemory(); long-sizeInBytes=fi.getSize(); //*setAttribute(“上传目录”,文件); //日期=新日期(); //SimpleDataFormat英尺= //新的简化格式(“E yyyy.MM.dd'at'hh:MM:ss a zzz”); //字符串s=ft.format(日期); //字符串filename=“bala”; //字符串filename1=s+“”+文件名; //字符串fileName1=file.getFileName(); //out.println(filename1); //重命名文件 //文件oldfile=新文件(s1); //out.println(“旧文件名..”+旧文件); //File newfile=新文件(s2); //out.println(“新文件名…”+新文件); //if(oldfile.renameTo(newfile)){ //filename=“bala”+file.separator+filename1; //写文件 如果(fileName.lastIndexOf(“\\”>)=0){ 文件=新文件(文件路径+ fileName.substring(fileName.lastIndexOf(“\\”); }否则{ 文件=新文件(文件路径+ fileName.substring(fileName.lastIndexOf(“\\”+1)); } fi.写入(文件); out.println(“成功上传文件。”+“
”; out.println(“上传的文件名:“+Filename+”
”; } } out.println(“”); out.println(“”); }捕获(例外情况除外){ 系统输出打印项次(ex); } } 受保护的void doGet(HttpServletRequest请求、HttpServletResponse响应)抛出ServletException、IOException、java.io.IOException{ 抛出新的ServletException(“GET方法用于”+ getClass().getName()+“:需要POST方法。”); } }
在浏览了您代码的注释行之后,我想我明白了您的意图

检查该文件是否已存在于文件夹中,如果是,则将旧文件重命名为其他文件,并在旧文件上写入新文件

如果是这样的话,

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.

您最好只使用html页面作为ui用途。
并在背面编写servlet代码。

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


你的问题是什么?