JSP上传文件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JSP上传文件相关的知识,希望对你有一定的参考价值。

jsp上传文件如果上传的文件小于10M 没有问题 如果大于10M就报异常:
org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size of 10000000 bytes exceeded; nested exception is org.apache.commons.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (10815787) exceeds the configured maximum (10000000)
应该是文件超过最大值 麻烦问下各位大侠 如果设置上传最大文件

======================================
jsp代码:
<input type="file" class="accept" name="file" id="file" />
java代码
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile file = multipartRequest.getFile("file");

参考技术A ServletFileUpload sfu = new ServletFileUpload(itemFactory);
// 设置上传文件的最大文件为10M
sfu.setSizeMax(0xA00000);
限制上传文件的的最大值的属性值设置
参考技术B 这里有一个无刷新多文件上传系统
里面可以判断文件多少 文件类型
里面有教程和源码

参考资料:http://www.blueidea.com/common/shoutbox/redir.asp?8=n&id=11280

本回答被提问者采纳
参考技术C 他说的对

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

【中文标题】如何使用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上传文件的主要内容,如果未能解决你的问题,请参考以下文章

JSP学习笔记:文件上传

JSP-超大文件上传-如何上传文件-大文件上传

怎么用jsp实现拖拽上传图片?

jsp上传文件

jsp WebUploader 分块上传

jsp WebUploader 分块上传