简体   繁体   English

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

[英]How to receive a file type parameter from html/jsp into a servlet

I want to take image as input into my web page.我想将图像作为输入到我的网页中。 I have written following code in my jsp for this :-为此,我在我的 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>

but I do not know how to receive the "image" parameter in a servlet that is whether it should be a input stream or file, I have no idea.但我不知道如何在 servlet 中接收“图像”参数,即它应该是输入流还是文件,我不知道。 Please tell me the correct code for it.请告诉我正确的代码。

Use Apache Commons File.使用 Apache 公共文件。 The form method must be method="POST".表单方法必须是method="POST"。 Then in your web.xml you need to map the request to your servlet:然后在您的 web.xml 中,您需要将请求映射到您的 servlet:

<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>

Then you write a class that extends HttpServlet and implement to doPost() method.然后编写一个扩展HttpServlet并实现 doPost() 方法的类。

well, just go here: http://www.codejava.net/java-ee/servlet/apache-commons-fileupload-example-with-servlet-and-jsp好吧,就去这里: http : //www.codejava.net/java-ee/servlet/apache-commons-fileupload-example-with-servlet-and-jsp

After painstaking efforts and google search I found a solution to my problem.经过艰苦的努力和谷歌搜索,我找到了解决问题的方法。 A page from Stackoverflow helped very much. Stackoverflow 的一个页面非常有帮助。 First I changed the get method of my form to post like this首先,我将表单的 get 方法更改为这样发布

<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>

Then I wrote the following servlet code.然后我写了下面的servlet代码。 We accept the <input type="file"> data as Part data in servlet.我们接受<input type="file">数据作为 servlet 中的 Part 数据。 Then we convert it to input stream.然后我们将其转换为输入流。 The input stream then can be saved in database.然后可以将输入流保存在数据库中。 Here is my Servlet:-这是我的 Servlet:-

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());
            }
        }

    }

}

After execution, it does the job successfully.执行后,它成功地完成了工作。 We accept the image from user and save it in database.我们接受来自用户的图像并将其保存在数据库中。 Hope this solution will help all :)希望这个解决方案对所有人都有帮助:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM