JSP文件数组以表格形式上传和重命名

时间:2017-09-26 13:47:42

标签: java file jsp

[HTML]

<form action="fileOK.jsp" method="post" enctype="multipart/form-data">
    <input type="file" name="file[]">
    <input type="file" name="file[]">
    <input type="file" name="file[]">
    <input type="submit">
</form>

[JSP]

<%@ page import="java.util.Enumeration" %>
<%@ page import="java.io.File" %>
<%@ page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy" %>
<%@ page import="com.oreilly.servlet.MultipartRequest" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title></title>
        <style></style>
        <script type="text/javascript"></script>
    </head>

    <body>
<%
    // Form의 file name이 배열로 넘어왔을 때는 Enumeration이 한 번만 실행됨.
    String savePath = "/uploads/";
    String realPath = application.getRealPath(savePath);

    String encType = "UTF-8";
    int maxSize = 1024 * 1024 * 100;

    try {
        MultipartRequest multipartRequest = new MultipartRequest(request, realPath, maxSize, encType, new DefaultFileRenamePolicy());
        Enumeration files = multipartRequest.getFileNames();
        File oldFile, newFile;

        int i = 0;       
        while (files.hasMoreElements()) {
            String realFileName = multipartRequest.getParameter("name");
            realFileName = realFileName + "_" + i + ".png";
            String name = (String) files.nextElement();

            oldFile = multipartRequest.getFile(name);
            newFile = new File(realPath + realFileName);
            oldFile.renameTo(newFile);
            i++;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

%>
    </body>
</html>

仅重命名了最后一个文件。 我知道String name =(String)files.nextElement()是file [] 我怎么解决这个问题? 如果表单输入文件的名称是file [],则getFileNames()返回一个。 救我这个问题!

1 个答案:

答案 0 :(得分:0)

尝试更改为:

<form action="fileOK.jsp" method="post" enctype="multipart/form-data">
    <input type="file" name="file1">
    <input type="file" name="file2">
    <input type="file" name="file3">
    <input type="submit">
</form>