JSP上传文件失败 [英] JSP upload File failed

查看:125
本文介绍了JSP上传文件失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将使用Servlet构建一个简单的jspfile来处理上传文件。在执行时,它显示以下消息

I am going to build up a simple jspfile to handle upload files using Servlet. When it comes to the execution, it shows the following message

demo Fail: org.apache.catalina.connector.RequestFacade cannot

 be cast to org.apache.tomcat.util.http.fileupload.RequestContext



<你能告诉我如何将HTTP请求转换为RequestContext吗?

Would you please tell me how to convert the HTTP request to RequestContext ?

以下是我的jsp首页代码

The below is my code for jsp front-page

    <%@ 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>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title Test Upload</title>
</head>
<body>

<form action="uploadFile" method="post" enctype="multipart/form-data">
    <input type="file" name="file" />
    <input type="submit" />
</form>

</body>
</html>

以下是我的Servlet代码

The below is my code for the Servlet

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.sql.*;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;

import javax.servlet.*;
import javax.servlet.http.*;

import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileItemFactory;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.RequestContext;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class getLogin
 */
public class uploadFile extends HttpServlet {

    private static final long serialVersionUID = 17864986468494864L;


    // location to store file uploaded
    private static final String UPLOAD_DIRECTORY = "upload";

    // upload settings

    public uploadFile() {
        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
        //doPost(request, response);
        //throw new ServletException("GET method used with " +  getClass( ).getName( )+": POST method required.");
        request.getRequestDispatcher("/WEB-INF/upload.jsp").forward(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("demo");

        if (!ServletFileUpload.isMultipartContent(request)) {
            // if not, we stop here
            PrintWriter writer = response.getWriter();
            writer.println("Error: Form must has enctype=multipart/form-data.");
            writer.flush();
            return;
        }

        // configures upload settings
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // sets temporary location to store files
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        ServletFileUpload upload = new ServletFileUpload(factory);


        // constructs the directory path to store upload file
        // this path is relative to application's directory
        String uploadPath = getServletContext().getRealPath("")+ File.separator + UPLOAD_DIRECTORY;

        // creates the directory if it does not exist
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }

        try {
            // parses the request's content to extract file data

            System.out.println(uploadPath);
            List<FileItem> formItems = upload.parseRequest((RequestContext)request);
            if (formItems != null && formItems.size() > 0) {
                // iterates over form's fields
                for (FileItem item : formItems) {
                    // processes only fields that are not form fields
                    if (!item.isFormField()) {
                        String fileName = new File(item.getName()).getName();
                        String filePath = uploadPath + File.separator + fileName;
                        File storeFile = new File(filePath);
                        // C:\tomcat\apache-tomcat-7.0.40\webapps\data\
                        // saves the file on disk
                        item.write(storeFile);
                        request.setAttribute("message","Upload has been done successfully!");
                        System.out.println("demo Success");
                    }
                }
            }
        } catch (Exception ex) {
            request.setAttribute("message","There was an error: " + ex.getMessage());
            System.out.println("demo Fail: " +   ex.getMessage() );
        }
    }


}


推荐答案

当您使用enctype = multipart / form-data从表单获取参数而不使用标准

This error attemp on Tomcat 7 and Servlet 3.0 when you are getting parameters from a Form with enctype=multipart/form-data without using standard

@WebServlet("/yourPattern")
@MultipartConfig
public class UploadFile extends HttpServlet { //...

然后使用Part对象

Part filePart = request.getPart("file"); // Retrieves <input type="file" name="file">
InputStream filecontent = filePart.getInputStream();

而不是

 List<FileItem> formItems = upload.parseRequest((RequestContext)request);
        if (formItems != null && formItems.size() > 0) {
            // iterates over form's fields
            for (FileItem item : formItems) {
                if (!item.isFormField()) { //...

请参阅此其他帖子以获取更多信息信息。

See this other post for further information.

这篇关于JSP上传文件失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆