如何在servlet中获取图像数组?

How to get array of images in servlet?

我正在使用单个上传按钮上传更多图片,例如下面的代码,

根据答案更新:

 package TeachChapter;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.sql.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
/**
 * Servlet implementation class ImageUploadToDB
 */
@WebServlet("/ImageUploadToDB")
public class ImageUploadToDB extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public ImageUploadToDB() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        System.out.println("Entered successfully:");
        final FileItemFactory factory = new DiskFileItemFactory();
        final ServletFileUpload fileUpload = new ServletFileUpload(factory);
        List items = null;
         Map<String, InputStream> fileMap = new HashMap<String, InputStream>();

        if (ServletFileUpload.isMultipartContent(request)) {

            // get the request content and iterate through
            try {
                items = fileUpload.parseRequest(request);
            } catch (FileUploadException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            if (items != null) {
                System.out.println("if0 successfully:");
                final Iterator iter = items.iterator();
                while (iter.hasNext()) {
                    System.out.println("while successfully:");
                    final FileItem item = (FileItem) iter.next();
                    // this is for non-file fields
                    if (item.isFormField()) {
                        System.out.println("if1 successfully:");
                    // logic for setting non-file fields
                    } else {
                        // item.getName() - gives file name
                        fileMap.put(item.getName(), item.getInputStream());
                        System.out.println("else successfully:");
                    }
                }
            }
        }


        try {
            System.out.println("try connection successfully:");

        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Connection con;
        con = DriverManager.getConnection("jdbc:mysql://localhost:3306/raptor1_5","root","");

        Set<String> keySet = fileMap.keySet();
        for (String fileName : keySet) {
            System.out.println("for successfully:");
        String sql ="INSERT INTO contacts (first_name, last_name, photo) values (?, ?, ?)" ; 
        PreparedStatement statement;

            statement = con.prepareStatement(sql);

             statement.setString(1, "mani");  
             statement.setString(2, "vasu"); 

            statement.setBlob(3, fileMap.get(fileName));


            int row = statement.executeUpdate();
            System.out.println("inserted successfully:");
        }
        }
         catch (SQLException e) {
            // TODO Auto-generated catch block
            System.out.println("errror is:"+e);
        }  



    }
}

OP :

Entered successfully:
try connection successfully:

我知道上面的代码完全错误,但我想在 servlet 页面中获取所有上传的图像以插入 mysql。

请帮帮我。

遇到过类似的问题 - 也许您可以进一步解决这个问题。

这是一个通用解决方案 - 您不知道输入请求中的附件数量。它迎合了如下多部分请求。

// imports
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;

// code flow
// HttpServletRequest request
final FileItemFactory factory = new DiskFileItemFactory();
final ServletFileUpload fileUpload = new ServletFileUpload(factory);
List items = null;
private Map<String, InputStream> fileMap = new HashMap<String, InputStream>();

if (ServletFileUpload.isMultipartContent(request)) {

    // get the request content and iterate through
    items = fileUpload.parseRequest(request);

    if (items != null) {
        final Iterator iter = items.iterator();
        while (iter.hasNext()) {
            final FileItem item = (FileItem) iter.next();
            // this is for non-file fields
            if (item.isFormField()) {

            // logic for setting non-file fields
            } else {
                // item.getName() - gives file name
                fileMap.put(item.getName(), item.getInputStream());
            }
        }
    }
}

//Here i will insert that images on by one to DB
Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/raptor1_5","root","");

Set<String> keySet = fileMap.keySet();
for (String fileName : keySet) {

String sql = "INSERT INTO contacts (photo) values (?)";  
PreparedStatement statement = con.prepareStatement(sql);  
statement.setBlob(1, fileMap.get(fileName));  
int row = statement.executeUpdate();  
}

fileMap 将包含您在请求中发送的所有文件。

如果您不介意文件名,您可以将实现从 HashMap 更改为 ArrayList 并相应地修改 for loop