Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jsp/3.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 如何使用JSP/Servlet将文件上载到服务器?_Java_Jsp_Jakarta Ee_Servlets_File Upload - Fatal编程技术网

Java 如何使用JSP/Servlet将文件上载到服务器?

Java 如何使用JSP/Servlet将文件上载到服务器?,java,jsp,jakarta-ee,servlets,file-upload,Java,Jsp,Jakarta Ee,Servlets,File Upload,如何使用JSP/Servlet将文件上载到服务器?我试过这个: FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List items = upload.parseRequest(request); // This line is where it died. 但是,我只获取文件名,而不获取文件内容。当我将enctyp

如何使用JSP/Servlet将文件上载到服务器?我试过这个:

FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = upload.parseRequest(request); // This line is where it died.

但是,我只获取文件名,而不获取文件内容。当我将
enctype=“multipart/form data”
添加到
中时,
request.getParameter()
返回
null

在研究过程中,我偶然发现。我试过这个:

FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = upload.parseRequest(request); // This line is where it died.
不幸的是,servlet在没有明确消息和原因的情况下引发了异常。以下是stacktrace:

SEVERE: Servlet.service() for servlet UploadServlet threw exception
javax.servlet.ServletException: Servlet execution threw an exception
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:313)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Thread.java:637)
介绍 要浏览并选择要上载的文件,您需要表单中的HTML
字段。如中所述,您必须使用
POST
方法,并且表单的
enctype
属性必须设置为
“多部分/表单数据”


提交此类表单后,当未设置
enctype
时,请求正文中的二进制多部分表单数据可用

在Servlet 3.0之前,Servlet API本机不支持
多部分/表单数据
。它只支持默认的表单类型
应用程序/x-www-form-urlencoded
。使用多部分表单数据时,
request.getParameter()
和consort都将返回
null
。这就是著名人物出现的地方

不要手动解析它! 从理论上讲,您可以自己分析请求主体。然而,这是一项精确而乏味的工作,需要精确的知识。你不应该试图自己做这件事,也不应该复制粘贴一些在互联网上其他地方找到的本地无库代码。许多在线资源在这方面都失败了,比如roseindia.net。另见。您更应该使用一个真正的库,它已经被数百万用户使用(并隐式测试!)多年了。这样一个库已经证明了它的健壮性

当您已经使用Servlet 3.0或更新版本时,请使用本机API 如果您至少使用了Servlet 3.0(Tomcat 7、Jetty 9、JBoss AS 6、GlassFish 3等),那么您可以使用提供的标准API来收集单个多部分表单数据项(大多数Servlet 3.0实现实际上都在封面下使用Apache Commons FileUpload!)。另外,通过
getParameter()
通常的方式可以使用标准格式字段

首先用注释您的servlet,使其能够识别和支持
multipart/form data
请求,从而使
getPart()
工作:

@WebServlet("/upload")
@MultipartConfig
public class UploadServlet extends HttpServlet {
    // ...
}
然后,实现其
doPost()
,如下所示:

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public void handleUpload(@RequestParam("file") MultipartFile file) throws IOException {
    if (!file.isEmpty()) {
            byte[] bytes = file.getBytes(); // alternatively, file.getInputStream();
            // application logic
    }
}
protectedvoiddopost(HttpServletRequest请求,HttpServletResponse响应)抛出ServletException,IOException{
String description=request.getParameter(“description”);//检索
Part filePart=request.getPart(“文件”);//检索
字符串文件名=路径.get(filePart.getSubmittedFileName()).getFileName().toString();//MSIE修复。
InputStream fileContent=filePart.getInputStream();
//…(在这里做你的工作)
}
注意
路径#getFileName()
。这是一个关于获取文件名的MSIE修复程序。此浏览器不正确地沿名称而不是仅沿文件名发送完整文件路径

private static String getSubmittedFileName(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;
}
如果您有一个用于多文件上传的
,请按如下方式收集它们(遗憾的是,没有像
request.getParts(“文件”)
这样的方法):

请注意MSIE关于获取文件名的修复。此浏览器不正确地沿名称而不是仅沿文件名发送完整文件路径

private static String getSubmittedFileName(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;
}
当您还没有使用Servlet3.0时,请使用ApacheCommonsFileUpload 如果您还没有使用Servlet3.0(是时候升级了吗?),通常的做法是使用解析多部分表单数据请求。它有一个很好的和(仔细地通过两者)。还有O'Reilly(“”
MultipartRequest
),但它有一些(小)错误,多年来不再积极维护。我不建议使用它。Apache Commons FileUpload仍在积极维护,目前非常成熟

为了使用Apache Commons FileUpload,您需要在WEB应用程序的
/WEB-INF/lib
中至少包含以下文件:

您最初的尝试很可能失败,因为您忘记了commons IO

下面是一个启动示例,在使用Apache Commons FileUpload时,
UploadServlet
doPost()
可能是什么样子:

protectedvoiddopost(HttpServletRequest请求,HttpServletResponse响应)抛出ServletException,IOException{
试一试{
列表项=新建ServletFileUpload(新建DiskFileItemFactory()).parseRequest(请求);
用于(文件项:项){
if(item.isFormField()){
//处理常规表单字段(输入type=“text | radio | checkbox | etc”,选择等)。
字符串fieldName=item.getFieldName();
String fieldValue=item.getString();
//…(在这里做你的工作)
}否则{
//处理表单文件字段(输入类型=“文件”)。
字符串fieldName=item.getFieldName();
字符串fileName=FilenameUtils.getName(item.getName());
InputStream fileContent=item.getInputStream();
//…(在这里做你的工作)
}
}
}捕获(文件上载异常){
抛出新的ServletException(“无法解析多部分请求。”,e);
}
// ...
}
非常重要的一点是,不要事先在同一请求上调用
getParameter()
getParameterMap()
getParameterValues()
getInputStream()
getReader()
等。否则,servlet容器将读取并解析请求主体,因此Apache Commons FileUpload将获得一个空的请求主体。另见a.o

请注意
FilenameUtils#getName()
。这是一个关于获取文件名的MSIE修复程序。这家浏览器公司
String description = getValue(request.getPart("description")); // Retrieves <input type="text" name="description">
public class ServletCommonfunctions extends HttpServlet implements
        Connections {

    private static final long serialVersionUID = 1L;

    public ServletCommonfunctions() {}

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

    public SortedMap<String, String> savefilesindirectory(
            HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        // Map<String, String> key_values = Collections.synchronizedMap( new
        // TreeMap<String, String>());
        SortedMap<String, String> key_values = new TreeMap<String, String>();
        String dist = null, fact = null;
        PrintWriter out = response.getWriter();
        File file;
        String filePath = "E:\\FSPATH1\\2KL06CS048\\";
        System.out.println("Directory Created   ????????????"
            + new File(filePath).mkdir());
        int maxFileSize = 5000 * 1024;
        int maxMemSize = 5000 * 1024;
        // Verify the content type
        String contentType = request.getContentType();
        if ((contentType.indexOf("multipart/form-data") >= 0)) {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            // maximum size that will be stored in memory
            factory.setSizeThreshold(maxMemSize);
            // Location to save data that is larger than maxMemSize.
            factory.setRepository(new File(filePath));
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // maximum file size to be uploaded.
            upload.setSizeMax(maxFileSize);
            try {
                // Parse the request to get file items.
                @SuppressWarnings("unchecked")
                List<FileItem> fileItems = upload.parseRequest(request);
                // Process the uploaded file items
                Iterator<FileItem> i = fileItems.iterator();
                while (i.hasNext()) {
                    FileItem fi = (FileItem) i.next();
                    if (!fi.isFormField()) {
                        // Get the uploaded file parameters
                        String fileName = fi.getName();
                        // 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);
                    } else {
                        key_values.put(fi.getFieldName(), fi.getString());
                    }
                }
            } catch (Exception ex) {
                System.out.println(ex);
            }
        }
        return key_values;
    }
}
fileItems = uploader.parseRequest(request);
Pasted from <http://osdir.com/ml/user-geronimo-apache/2011-03/msg00026.html> 



<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<web:web-app xmlns:app="http://geronimo.apache.org/xml/ns/j2ee/application-2.0" xmlns:client="http://geronimo.apache.org/xml/ns/j2ee/application-client-2.0" xmlns:conn="http://geronimo.apache.org/xml/ns/j2ee/connector-1.2" xmlns:dep="http://geronimo.apache.org/xml/ns/deployment-1.2" xmlns:ejb="http://openejb.apache.org/xml/ns/openejb-jar-2.2" xmlns:log="http://geronimo.apache.org/xml/ns/loginconfig-2.0" xmlns:name="http://geronimo.apache.org/xml/ns/naming-1.2" xmlns:pers="http://java.sun.com/xml/ns/persistence" xmlns:pkgen="http://openejb.apache.org/xml/ns/pkgen-2.1" xmlns:sec="http://geronimo.apache.org/xml/ns/security-2.0" xmlns:web="http://geronimo.apache.org/xml/ns/j2ee/web-2.0.1">
    <dep:environment>
        <dep:moduleId>
            <dep:groupId>DataStar</dep:groupId>
            <dep:artifactId>DataStar</dep:artifactId>
            <dep:version>1.0</dep:version>
            <dep:type>car</dep:type>
        </dep:moduleId>

<!--Don't load commons-io or fileupload from parent classloaders-->
        <dep:hidden-classes>
            <dep:filter>org.apache.commons.io</dep:filter>
            <dep:filter>org.apache.commons.fileupload</dep:filter>
        </dep:hidden-classes>
        <dep:inverse-classloading/>        


    </dep:environment>
    <web:context-root>/DataStar</web:context-root>
</web:web-app>
<form action="upload" method="post" enctype="multipart/form-data">
 <input type="file" name="fileattachments"  multiple="multiple"/>
 <input type="submit" />
</form>
<servlet>
    <servlet-name>jsp</servlet-name>
    <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
    <multipart-config>
      <max-file-size>3145728</max-file-size>
      <max-request-size>5242880</max-request-size>
    </multipart-config>
    <init-param>
        <param-name>fork</param-name>
        <param-value>false</param-value>
    </init-param>
    <init-param>
        <param-name>xpoweredBy</param-name>
        <param-value>false</param-value>
    </init-param>
    <load-on-startup>3</load-on-startup>
</servlet>
    <multipart-config>
      <max-file-size>3145728</max-file-size>
      <max-request-size>5242880</max-request-size>
    </multipart-config>
<form method="post" enctype="multipart/form-data" name="Form" >

  <input type="file" name="fFoto" id="fFoto" value="" /></td>
  <input type="file" name="fResumen" id="fResumen" value=""/>
    InputStream isFoto = request.getPart("fFoto").getInputStream();
    InputStream isResu = request.getPart("fResumen").getInputStream();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte buf[] = new byte[8192];
    int qt = 0;
    while ((qt = isResu.read(buf)) != -1) {
      baos.write(buf, 0, qt);
    }
    String sResumen = baos.toString();
<form action="UploadFileServlet" method="post">
  <input type="text" name="description" />
  <input type="file" name="file" />
  <input type="submit" />
</form>
     package com.abc..servlet;

import java.io.File;
---------
--------


/**
 * Servlet implementation class UploadFileServlet
 */
public class UploadFileServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public UploadFileServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.sendRedirect("../jsp/ErrorPage.jsp");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub

            PrintWriter out = response.getWriter();
            HttpSession httpSession = request.getSession();
            String filePathUpload = (String) httpSession.getAttribute("path")!=null ? httpSession.getAttribute("path").toString() : "" ;

            String path1 =  filePathUpload;
            String filename = null;
            File path = null;
            FileItem item=null;


            boolean isMultipart = ServletFileUpload.isMultipartContent(request);

            if (isMultipart) {
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                String FieldName = "";
                try {
                    List items = upload.parseRequest(request);
                    Iterator iterator = items.iterator();
                    while (iterator.hasNext()) {
                         item = (FileItem) iterator.next();

                            if (fieldname.equals("description")) {
                                description = item.getString();
                            }
                        }
                        if (!item.isFormField()) {
                            filename = item.getName();
                            path = new File(path1 + File.separator);
                            if (!path.exists()) {
                                boolean status = path.mkdirs();
                            }
                            /* START OF CODE FRO PRIVILEDGE*/

                            File uploadedFile = new File(path + Filename);  // for copy file
                            item.write(uploadedFile);
                            }
                        } else {
                            f1 = item.getName();
                        }

                    } // END OF WHILE 
                    response.sendRedirect("welcome.jsp");
                } catch (FileUploadException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                } 
            }   
    }

}
DiskFileUpload upload=new DiskFileUpload();
String loc="./webapps/prjct name/server folder/"+contentid+extension;
File uploadFile=new File(loc);
item.write(uploadFile);
// apache commons-fileupload to handle file upload
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(new File(DataSources.TORRENTS_DIR()));
ServletFileUpload fileUpload = new ServletFileUpload(factory);

List<FileItem> items = fileUpload.parseRequest(req.raw());
FileItem item = items.stream()
  .filter(e ->
  "the_upload_name".equals(e.getFieldName()))
  .findFirst().get();
String fileName = item.getName();

item.write(new File(dir, fileName));
log.info(fileName);
<form action="upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file" />
    <input type="submit" value="Upload"/>
</form>
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public void handleUpload(@RequestParam("file") MultipartFile file) throws IOException {
    if (!file.isEmpty()) {
            byte[] bytes = file.getBytes(); // alternatively, file.getInputStream();
            // application logic
    }
}
<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="UploadServlet" method="post"
                        enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" value="Upload File" />
</form>
</body>
</html> 
// Import required java libraries
import java.io.*;
import java.util.*;

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 boolean isMultipart;
   private String filePath;
   private int maxFileSize = 50 * 1024;
   private int maxMemSize = 4 * 1024;
   private File file ;

   public void init( ){
      // Get the file location where it would be stored.
      filePath = 
             getServletContext().getInitParameter("file-upload"); 
   }
   public void doPost(HttpServletRequest request, 
               HttpServletResponse response)
              throws ServletException, java.io.IOException {
      // Check that we have a file upload request
      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();
      // maximum size that will be stored in memory
      factory.setSizeThreshold(maxMemSize);
      // Location to save data that is larger than maxMemSize.
      factory.setRepository(new File("c:\\temp"));

      // Create a new file upload handler
      ServletFileUpload upload = new ServletFileUpload(factory);
      // maximum file size to be uploaded.
      upload.setSizeMax( maxFileSize );

      try{ 
      // Parse the request to get file items.
      List 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();
            // 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("Uploaded Filename: " + fileName + "<br>");
         }
      }
      out.println("</body>");
      out.println("</html>");
   }catch(Exception ex) {
       System.out.println(ex);
   }
   }
   public void doGet(HttpServletRequest request, 
                       HttpServletResponse response)
        throws ServletException, java.io.IOException {

        throw new ServletException("GET method used with " +
                getClass( ).getName( )+": POST method required.");
   } 
}
<servlet>
   <servlet-name>UploadServlet</servlet-name>
   <servlet-class>UploadServlet</servlet-class>
</servlet>

<servlet-mapping>
   <servlet-name>UploadServlet</servlet-name>
   <url-pattern>/UploadServlet</url-pattern>
</servlet-mapping>
<form action="/handleform" method="post" enctype="multipart/form-data">
  <input type="text" name="name" />
  <input type="text" name="age" />
  <input type="file" name="file" />
  <input type="submit" />
</form>
@Controller
public class FormController {
    @RequestMapping(value="/handleform",method= RequestMethod.POST)
    ModelAndView register(@RequestParam String name, @RequestParam int age, @RequestParam MultipartFile file)
            throws ServletException, IOException {

        System.out.println(name);
        System.out.println(age);
        if(!file.isEmpty()){
            byte[] bytes = file.getBytes();
            String filename = file.getOriginalFilename();
            BufferedOutputStream stream =new BufferedOutputStream(new FileOutputStream(new File("D:/" + filename)));
            stream.write(bytes);
            stream.flush();
            stream.close();
        }
        return new ModelAndView("index");
    }
}
  <%
  if (request.getContentType()==null) return;
  // for input type=text controls
  String v_Text = 
  (new BufferedReader(new InputStreamReader(request.getPart("Text1").getInputStream()))).readLine();    

  // for input type=file controls
  InputStream inStr = request.getPart("File1").getInputStream();
  char charArray[] = new char[inStr.available()];
  new InputStreamReader(inStr).read(charArray);
  String contents = new String(charArray);
  %>
<form action="Controller" method="post" enctype="multipart/form-data">
     <label class="file-upload"> Click here to upload an Image </label>
     <input type="file" name="file" id="file" required> 
</form>
@MultipartConfig

public class Controller extends HttpServlet {

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

    private void addProduct(HttpServletRequest request, HttpServletResponse response) {
        Part filePart = request.getPart("file");
        String imageName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();

        String imageSavePath = "specify image path to save image"; //path to save image
        FileOutputStream outputStream = null;
        InputStream fileContent = null;

        try {
            outputStream = new FileOutputStream(new File(imageSavePath + File.separator + imageName));
            //creating a new file with file path and the file name
            fileContent = filePart.getInputStream();
            //getting the input stream
            int readBytes = 0;
            byte[] readArray = new byte[1024];
            //initializing a byte array with size 1024

            while ((readBytes = fileContent.read(readArray)) != -1) {
                outputStream.write(readArray, 0, readBytes);
            }//this loop will write the contents of the byte array unitl the end to the output stream
        } catch (Exception ex) {
            System.out.println("Error Writing File: " + ex);
        } finally {
            if (outputStream != null) {
                outputStream.close();
                //closing the output stream
            }
            if (fileContent != null) {
                fileContent.close();
                //clocsing the input stream
            }
        }
    }
}