java - 文件无法正确上传

标签 java html jsp servlets

这里我想将我的文件上传到我的上传文件夹中,但在我的场景中,它无法存储在该文件夹中。文件名会打印在控制台中,但文件不会存储在上传文件夹中。在开发者工具控制台中,我收到名为“无法加载资源:服务器响应状态为 404(未找到)”的错误。

DemoForm.java

    package controller;

import java.io.*;


import java.util.* ;

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;



/**
 * Servlet implementation class DemoForm
 */
@WebServlet("/DemoForm")
@MultipartConfig(
        fileSizeThreshold = 1024 * 1024 * 10, //10MB
        maxFileSize = 1024 * 1024 * 50, //50MB
        maxRequestSize = 1024 * 1024 * 100 //100MB
        )

public class DemoForm extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static final String UPLOAD_DIR = "upload";



    /**
     * @see HttpServlet#HttpServlet()
     */
    public DemoForm() { 
        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
        //response.getWriter().append("Served at: ").append(request.getContextPath());
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute("username", request.getParameter("username"));
        request.setAttribute("password", request.getParameter("password"));
        request.setAttribute("sex", request.getParameter("sex"));
        request.setAttribute("favious", Arrays.toString(request.getParameterValues("favious")));
        request.setAttribute("description", request.getParameter("description"));
        request.setAttribute("experience", request.getParameter("experience"));
        request.setAttribute("fileName", uploadFile(request));
        request.getRequestDispatcher("form_result.jsp").forward(request, response);

    }

    private String uploadFile(HttpServletRequest request) {

        String fileName = "";

        try {
            Part filePart = request.getPart("photo");
            fileName = getfileName(filePart);
            String applicationPath = request.getServletContext().getRealPath("");
            String basePath = applicationPath + File.separator + UPLOAD_DIR 
                    + File.separator;
            // creates the save directory if it does not exists
            File fileSaveDir = new File(basePath);
            if (!fileSaveDir.exists()) {
                fileSaveDir.mkdir();
            }
            InputStream inputStream = null;
            OutputStream outputStream = null;
            try {
                File outputFilePath = new File(basePath + fileName);
                inputStream =filePart.getInputStream();
                outputStream = new FileOutputStream(outputFilePath);
                int read = 0;
                final byte[] bytes = new byte[1024];
                while((read = inputStream.read(bytes))!= -1) {
                    outputStream.write(bytes,0,read);
                }
            }catch(Exception ex) {
                ex.printStackTrace();
                fileName="";

            }finally {
                if(outputStream != null) {
                    outputStream.close();
                }
                if(inputStream != null) {
                    inputStream.close();
                }
            }

        }catch(Exception ex){
            fileName = "";
        }
        return fileName;
    }


    private String getfileName(Part part) {
        final String partHeader = part.getHeader("content-disposition");
        System.out.println("*****partHeader:" + partHeader);
        for(String content : part.getHeader("content-disposition").split(";")) {
            if(content.trim().startsWith("fileName")) {
                return content.substring(content.indexOf('=')+ 1).trim()
                        .replace("\"", "");
            }
        }
        return null;
    }



}

Form.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Upload file</title>
</head>
<body>
    <form method="post" action="DemoForm" enctype="multipart/form-data">
        <table border="0" cellpadding="2" cellspacing="2" width="300">
            <tr>
                <td> username:</td>
                <td><input type="text" name="username"/></td>
            </tr>
            <tr>
                <td> Password:</td>
                <td><input type="password" name="password"/></td>
            </tr>

            <tr>
                <td valign="top"> Sex </td>
                <td>
                    <input type="radio" name="sex" value="male" checked="checked"/>Male
                    <br>
                    <input type="radio" name="sex" value="female"/>Female
                </td>
            </tr>
            <tr>
                <td valign="top"> Favious </td>
                <td>
                    <input type="checkbox" name="favious" value="fav1"/>Favios 1<br>
                    <input type="checkbox" name="favious" value="fav2"/>Favios 2<br>
                    <input type="checkbox" name="favious" value="fav1"/>Favios 3<br>
                    <input type="checkbox" name="favious" value="fav1"/>Favios 4<br>
                    <input type="checkbox" name="favious" value="fav1"/>Favios 5<br>
                </td>
            </tr>
            <tr>
                <td valign="top"> Description:</td>
                <td><textarea rows="10" cols="20" name="description"></textarea></td>
            </tr>
            <tr>
                <td>Experiences</td>
                <td>
                    <select name="experience">
                        <option value="1"> 1 year </option>
                        <option value="2"> 2 year </option>
                        <option value="3"> 3 year </option>
                        <option value="4"> 4 year </option>
                    </select>
                </td>
            </tr>

            <tr>
                <td valign="top"> Photo</td>
                <td><input type="file" name="photo "/></td>
            </tr>
            <tr>
                <td>&nbsp</td>
                <td><input type="submit" name="save"/></td>
            </tr>
        </table>
    </form>
</body>
</html>

Form_result.jsp

[<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@page isELIgnored="false" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
        <h3>Account Information</h3>
        <table border="0" cellpadding="2" cellspacing="2" width="300">
            <tr>
                <td>Username</td>
                <td> ${username}</td>
            </tr>

            <tr>
                <td>Password</td>
                <td> ${password}</td>
            </tr>
            <tr>
                <td valign="top">Sex</td>
                <td> ${sex}</td>
            </tr>
            <tr>
                <td valign="top">Favious</td>
                <td> ${favious}</td>
            </tr>
            <tr>
                <td valign="top">Description</td>
                <td> ${description}</td>
            </tr>

            <tr>
                <td>Experience</td>
                <td> ${experience}</td>
            </tr>
            <tr>
                <td valign="top">Photo</td>
                <td><img src="upload/${fileName}"></td>
            </tr>
        </table>
</body>
</html>][1]

最佳答案

我认为错误不在您的文件上传中。您的servlet 尚未收到您的请求。只需注释掉所有代码并检查您的 doPost 是否正常工作?检查您正在访问的 URL。

关于java - 文件无法正确上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60630953/

相关文章:

java - 找到每个本地 Eclipse 工作区

python - 如何将python文本添加到HTML网站?

javascript - Ctrl + Enter 在 TEXTAREA 中使用 jQuery

java - Spring MVC : Any way to get generated html file before you send it to client?

javascript - 在 Javascript 中使用 Java

java - 如何通过 arquillian.xml 中的限定符选择容器?

java - for() 函数中的 ":"

java - Java异步文件写入PipedOutputStream/PipedInputStream(或Reader/Writer)与BlockingQueue的异同

html - 具有悬停效果的图像出现在标题上方时

java - 如何在jsp页面加载时调用servlet?