Java 如何将文件类型参数从html/jsp接收到servlet中

Java 如何将文件类型参数从html/jsp接收到servlet中,java,Java,我想把图像作为输入到我的网页中。我在jsp中为此编写了以下代码:- <form action="Upload" method="get" enctype="multipart/form-data"> Image<input type="file" name="image" accept="image/jpg" id="image"> <input type="submit" value="submit"> </form> 形象

我想把图像作为输入到我的网页中。我在jsp中为此编写了以下代码:-

<form action="Upload" method="get" enctype="multipart/form-data">
    Image<input type="file" name="image" accept="image/jpg" id="image">
    <input type="submit" value="submit">
</form>

形象
但我不知道如何在servlet中接收“image”参数,即它应该是输入流还是文件,我不知道。请告诉我正确的代码。

使用Apache Commons文件。
<form action="Upload" method="get" enctype="multipart/form-data">
    Image<input type="file" name="image" accept="image/jpg" id="image">
    <input type="submit" value="submit">
</form>
表单方法必须是method=“POST”。 然后在web.xml中,需要将请求映射到servlet:

<form action="Upload" method="get" enctype="multipart/form-data">
    Image<input type="file" name="image" accept="image/jpg" id="image">
    <input type="submit" value="submit">
</form>
<servlet>
        <servlet-name>MyServlet</servlet-name>
        <servlet-class>com.stackoverflow.MyServletClass</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>MyServlet</servlet-name>
        <url-pattern>/Upload</url-pattern>
</servlet-mapping>

MyServlet
com.stackoverflow.MyServletClass
MyServlet
/上传
然后编写一个类来扩展
HttpServlet
,并实现doPost()方法

<form action="Upload" method="get" enctype="multipart/form-data">
    Image<input type="file" name="image" accept="image/jpg" id="image">
    <input type="submit" value="submit">
</form>

好吧,就到这里:

经过艰苦的努力和谷歌搜索,我找到了解决问题的办法。Stackoverflow的一页非常有用。首先,我将表单的get方法更改为如下方式发布

<form action="Upload" method="get" enctype="multipart/form-data">
    Image<input type="file" name="image" accept="image/jpg" id="image">
    <input type="submit" value="submit">
</form>
<form action="Upload" method="post" enctype="multipart/form-data">
    Image<input type="file" name="image" id="image" accept="image/jpg">
    <input type="submit" value="submit">
</form>

形象
然后我编写了以下servlet代码。我们接受
数据作为servlet中的部分数据。然后我们将其转换为输入流。然后可以将输入流保存在数据库中。这是我的Servlet:-

<form action="Upload" method="get" enctype="multipart/form-data">
    Image<input type="file" name="image" accept="image/jpg" id="image">
    <input type="submit" value="submit">
</form>
package controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import model.ConnectionManager;

@MultipartConfig(location="/tmp", fileSizeThreshold=1048576, maxFileSize=20848820, maxRequestSize=418018841)
public class Upload extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Part filePart=request.getPart("image");`// Retrieves <input type="file" name="image">`
        String filePath = filePart.getSubmittedFileName();//Retrieves complete file name with path and directories 
        Path p = Paths.get(filePath); //creates a Path object
        String fileName = p.getFileName().toString();//Retrieves file name from Path object
        InputStream fileContent = filePart.getInputStream();//converts Part data to input stream

        Connection conn=ConnectionManager.getConnection();
        int  len=(int) filePart.getSize();
        String query = ("insert into IMAGETABLE(ID,NAME,LENGTH,IMAGE) VALUES(?,?,?,?)");


        try {
            PreparedStatement pstmt = conn.prepareStatement(query);
            pstmt.setInt(1, 5);
            pstmt.setString(2, fileName);
            pstmt.setInt(3, len);
            pstmt.setBinaryStream(4, fileContent, len);
            success=pstmt.executeUpdate();
        } catch (SQLException ex) {
            System.out.println("Error : "+ex.getMessage());
        }finally{
            try{
                if(fileContent!=null)fileContent.close();
                if(conn!=null)conn.close();
            }catch(IOException | SQLException ex){
                System.out.println("Error : "+ex.getMessage());
            }
        }

    }

}
包装控制器;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.PrintWriter;
导入java.nio.file.Path;
导入java.nio.file.path;
导入java.sql.Connection;
导入java.sql.PreparedStatement;
导入java.sql.SQLException;
导入javax.servlet.ServletException;
导入javax.servlet.annotation.MultipartConfig;
导入javax.servlet.http.HttpServlet;
导入javax.servlet.http.HttpServletRequest;
导入javax.servlet.http.HttpServletResponse;
导入javax.servlet.http.Part;
导入model.ConnectionManager;
@MultipartConfig(location=“/tmp”,fileSizeThreshold=1048576,maxFileSize=20848820,maxRequestSize=418018841)
公共类上载扩展了HttpServlet{
@凌驾
受保护的void doPost(HttpServletRequest请求、HttpServletResponse响应)
抛出ServletException、IOException{
Part filePart=request.getPart(“图像”);`//检索`
字符串filePath=filePart.getSubmittedFileName();//检索包含路径和目录的完整文件名
Path p=Path.get(filePath);//创建一个Path对象
String fileName=p.getFileName().toString();//从路径对象检索文件名
InputStream fileContent=filePart.getInputStream();//将零件数据转换为输入流
Connection conn=ConnectionManager.getConnection();
int len=(int)filePart.getSize();
字符串查询=(“插入到IMAGETABLE(ID、名称、长度、图像)值(?,?,?)”;
试一试{
PreparedStatement pstmt=conn.prepareStatement(查询);
pstmt.setInt(1,5);
pstmt.setString(2,文件名);
pstmt.setInt(3,len);
pstmt.setBinaryStream(4,fileContent,len);
success=pstmt.executeUpdate();
}catch(SQLException-ex){
System.out.println(“错误:+ex.getMessage());
}最后{
试一试{
如果(fileContent!=null)fileContent.close();
如果(conn!=null)连接关闭();
}catch(IOException | SQLException ex){
System.out.println(“错误:+ex.getMessage());
}
}
}
}

执行之后,它成功地完成了任务。我们接受来自用户的图像并将其保存在数据库中。希望此解决方案能帮助所有人:)

可能重复的感谢杰克:)。我急切地需要它,我试过了,但它不起作用。我正在尝试上载一个图像文件。还有什么建议……哪部分不起作用?你会犯什么错误?您是否使用post as方法?我的意思是MyServletClass扩展了HttpServlet。我的问题不同。我需要将图像文件保存在sql server数据库中。您提供的示例链接没有提供该解决方案。我得到了不同类型的servlet错误。再次感谢您的支持。
<form action="Upload" method="get" enctype="multipart/form-data">
    Image<input type="file" name="image" accept="image/jpg" id="image">
    <input type="submit" value="submit">
</form>