文件上传处理程序

时间:2014-04-03 21:16:24

标签: java jsp file-upload

这是文件上传处理程序的代码 这在我的服务器上工作正常,但在上传文件后,它只显示文件已成功上传 但我也想显示上传文件的名称

 import java.io.File;
 import java.io.IOException;
 import java.util.List;
 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;

public class FileUploadHandler extends HttpServlet {
private final String UPLOAD_DIRECTORY = "C:/uploads";

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

    //process only if its multipart content
    if(ServletFileUpload.isMultipartContent(request)){
        try {
            List<FileItem> multiparts = new ServletFileUpload(
                                     new DiskFileItemFactory()).parseRequest(request);

            for(FileItem item : multiparts){
                if(!item.isFormField()){
                    String name = new File(item.getName()).getName();
                    item.write( new File(UPLOAD_DIRECTORY + File.separator + name));
                }
            }

  //File uploaded successfully

           request.setAttribute("message", "File Uploaded Successfully");
        } catch (Exception ex) {
           request.setAttribute("message", "File Upload Failed due to " + ex);
        }          

    }else{
        request.setAttribute("message",
                             "Sorry this Servlet only handles file upload request");
    }

    request.getRequestDispatcher("/done.jsp").forward(request, response);

}

}

2 个答案:

答案 0 :(得分:1)

item.getName()存储在变量中供以后使用。由于您使用的是循环,因此如果有任何文件名,您必须跟踪多个文件名。

   String fileNames = ""; //to keep list of filenames
   for(FileItem item : multiparts){
            if(!item.isFormField()){
                fileNames += item.getName() + "; "; //add filename to string
                String name = new File(item.getName()).getName();
                item.write( new File(UPLOAD_DIRECTORY + File.separator + name));
            }
        }
    .....
    .....
    request.setAttribute("message", "File(s) Uploaded Successfully: " + fileNames );

答案 1 :(得分:0)

这段代码可以帮到你!

private static String getFileName(Part part) {
    for (String cd : part.getHeader("content-disposition").split(";")) {
        if (cd.trim().startsWith("filename")) {
            String filename = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
            return filename.substring(filename.lastIndexOf('/') + 1).substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
        }
    }
    return null;
}