如何使用jsp和servlet将多个图像上传到文件夹[重复]

Posted

技术标签:

【中文标题】如何使用jsp和servlet将多个图像上传到文件夹[重复]【英文标题】:how to upload multiple images into folder using jsp and servlet [duplicate] 【发布时间】:2015-06-18 14:13:21 【问题描述】:

我想使用 jsp 和 servlet 将多张图片上传到服务器文件夹

我可以上传单张图片,但我无法上传多张图片

请帮帮我

【问题讨论】:

【参考方案1】:

试试下面的代码(Apache commons 文件上传)

index.jsp

<html>
 <head><title>Upload page</title></head><body>
 <form action="UploadServlet" method="post" enctype="multipart/form-data" name="form1" id="form1">
   <center>
   <table border="1">
       <tr>
           <td align="center"><b>Multipale file Uploade</td>
       </tr>
       <tr>
           <td>
               Select file: <input name="file" type="file" id="file">
           </td>
       </tr>
       <tr>
          <td>
             Select file:<input name="file" type="file" id="file">
          </td>
        <tr>
           <td>
              Select file:<input name="file" type="file" id="file">
           </td>
         </tr>
         <tr>
            <td align="center">
               <input type="submit" name="Submit" value="Submit files"/>
            </td>
         </tr>
    </table>
    <center>
 </form>
 </body>
 </html>

或者您也可以使用下面的jsp代码(如果您正在使用此代码按ctrl选择多个图像)

<html>
 <head><title>Upload page</title></head><body>
 <form action="UploadServlet" method="post" enctype="multipart/form-data" name="form1" id="form1">
   <center>
   <table border="1">
       <tr>
           <td align="center"><b>Multipale file Uploade</td>
       </tr>
       <tr>
           <td>
               Specify file: <input name="file" type="file" id="file" multiple>
           </td>
       </tr>
         <tr>
            <td align="center">
               <input type="submit" name="Submit" value="Submit files"/>
            </td>
         </tr>
    </table>
    <center>
 </form>
 </body>
 </html>

还有 UploadServlet.java

package com;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

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.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
        doPost(request, response);
    

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (!isMultipart) 
         else 
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = null;
            try 
                items = upload.parseRequest(request);
                 catch (FileUploadException e) 
                    e.printStackTrace();
                
            Iterator itr = items.iterator();
            while (itr.hasNext()) 
                FileItem item = (FileItem) itr.next();
                if (item.isFormField()) 
                 else 
                    try 
                    String itemName = item.getName();
                    File savedFile = new File("D:\\"+itemName);
                    item.write(savedFile);  
                 catch (Exception e) 
                    e.printStackTrace();
                
            
        
    
    

希望对你有帮助!!!

【讨论】:

【参考方案2】:

这里是示例代码:

Coding for uploadform.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"     "http://www.w3.org/TR/html4/loose.dtd"> 
<html>
<head>
  <title>Image Upload</title>
  <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<form action="FileUploadServlet" method="post" enctype="multipart/form-data">
    <table  align="center" border=0>
       <tr>
       <td align="center" colspan=2>
            Image Details</td>
       </tr>
       <tr>
           <td>First Name </td>
       <td>
           <input type="input" name="firstname">
       </td>
   </tr>
   <tr>
       <td>Last Name </td>
       <td>
           <input type="input" name="lastname">
       </td>
   </tr>
   <tr>
       <td>Image Link: </td>
       <td>
           <input type="file" name="file">
       </td>
   </tr>
   <tr>
       <td></td>
       <td>
          <input type="submit" name="submit" value="Submit"></td>
       </tr>
   </table>
</form>
</body>
</html>

You need to set enctype of form tag to "multipart/form-data" it tells     that form contain multipart data.
This page contain two text fields for first name and last name and one file type field for files, after submitting the form data send to FileUploadServlet servlet where all other processing is to be done.

Coding for FileUploadServlet.java:


import java.io.PrintWriter;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;


@WebServlet("/FileUploadServlet")
@MultipartConfig(fileSizeThreshold=1024*1024*2, // 2MB
             maxFileSize=1024*1024*10,      // 10MB
             maxRequestSize=1024*1024*50)

public class FileUploadServlet extends HttpServlet 
private static final String SAVE_DIR="images";



protected void doPost(HttpServletRequest request, HttpServletResponse    response)
        throws ServletException, IOException, ClassNotFoundException,     SQLException 
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
        String savePath = "C:" + File.separator + SAVE_DIR;
            File fileSaveDir=new File(savePath);
            if(!fileSaveDir.exists())
                fileSaveDir.mkdir();
            
        String firstName=request.getParameter("firstname");
        String lastName=request.getParameter("lastname");
        Part part=request.getPart("file");
        String fileName=extractFileName(part);
        part.write(savePath + File.separator + fileName);
       /* 
        //You need this loop if you submitted more than one file 
        for (Part part : request.getParts()) 
        String fileName = extractFileName(part);
        part.write(savePath + File.separator + fileName);
    */
       try

Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306    /UploadFile","root","root");
        String query="INSERT INTO customerDetail (first_name, last_name, file) values (?, ?, ?)";

            PreparedStatement pst;
            pst=con.prepareStatement(query);
            pst.setString(1, firstName);
            pst.setString(2,lastName);
            String filePath= savePath + File.separator + fileName ;
            pst.setString(3,filePath);
            pst.executeUpdate();

catch(Exception e)
        

    // file name of the upload file is included in content-disposition     header like this:
//form-data; name="dataFile"; filename="PHOTO.JPG"
private String extractFileName(Part part) 
    String contentDisp = part.getHeader("content-disposition");
    String[] items = contentDisp.split(";");
    for (String s : items) 
        if (s.trim().startsWith("filename")) 
            return s.substring(s.indexOf("=") + 2, s.length()-1);
        
    
    return "";


【讨论】:

thanx 兄弟...但我想同时上传多个文件 我在评论部分提到过,检查一下。 我不能选择多个文件兄弟

以上是关于如何使用jsp和servlet将多个图像上传到文件夹[重复]的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 JSP/Servlet 和 Ajax 将文件上传到服务器?

如何以多部分形式将画布图像上传到 java servlet?

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

JSP学习笔记:文件上传

如何使用 NodeJS 将文件或图像上传到服务器

jsp如何将图片上传到服务器某个文件夹里面,而路径存到mysql数据库中,然后将数据库中的图片显示到另一页面