为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

繁星coding 2019-05-21 13:36:36
如何使用JSP / Servlet将文件上传到服务器?如何使用JSP / Servlet将文件上传到服务器?我试过这个:<form action="upload" method="post">    <input type="text" name="description" />    <input type="file" name="file" />    <input type="submit" /></form>但是,我只获取文件名,而不是文件内容。当我添加  enctype="multipart/form-data"到<form>,然后request.getParameter()返回null。在研究期间,我偶然发现了Apache Common FileUpload。我试过这个:FileItemFactory factory = new DiskFileItemFactory();ServletFileUpload upload = new ServletFileUpload(factory);List items = upload.parseRequest(request); // This line is where it died.不幸的是,servlet抛出了一个没有明确消息和原因的异常。这是堆栈跟踪:SEVERE: Servlet.service() for servlet UploadServlet threw exceptionjavax.servlet.ServletException: Servlet execution threw an exception    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:313)    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)    at java.lang.Thread.run(Thread.java:637)
查看完整描述

5 回答

?
墨色风雨

TA贡献1853条经验 获得超6个赞

我正在为每个 Html表单使用公共Servlet,无论它是否有附件。此Servlet返回一个TreeMap键,其中键是jsp名称参数和值是用户输入并将所有附件保存在固定目录中,稍后您重命名所选目录.Here Connections是具有连接对象的自定义接口。我想这会对你有所帮助


public class ServletCommonfunctions extends HttpServlet implements

        Connections {


    private static final long serialVersionUID = 1L;


    public ServletCommonfunctions() {}


    protected void doPost(HttpServletRequest request,

            HttpServletResponse response) throws ServletException,

            IOException {}


    public SortedMap<String, String> savefilesindirectory(

            HttpServletRequest request, HttpServletResponse response)

            throws IOException {

        // Map<String, String> key_values = Collections.synchronizedMap( new

        // TreeMap<String, String>());

        SortedMap<String, String> key_values = new TreeMap<String, String>();

        String dist = null, fact = null;

        PrintWriter out = response.getWriter();

        File file;

        String filePath = "E:\\FSPATH1\\2KL06CS048\\";

        System.out.println("Directory Created   ????????????"

            + new File(filePath).mkdir());

        int maxFileSize = 5000 * 1024;

        int maxMemSize = 5000 * 1024;

        // Verify the content type

        String contentType = request.getContentType();

        if ((contentType.indexOf("multipart/form-data") >= 0)) {

            DiskFileItemFactory factory = new DiskFileItemFactory();

            // maximum size that will be stored in memory

            factory.setSizeThreshold(maxMemSize);

            // Location to save data that is larger than maxMemSize.

            factory.setRepository(new File(filePath));

            // Create a new file upload handler

            ServletFileUpload upload = new ServletFileUpload(factory);

            // maximum file size to be uploaded.

            upload.setSizeMax(maxFileSize);

            try {

                // Parse the request to get file items.

                @SuppressWarnings("unchecked")

                List<FileItem> fileItems = upload.parseRequest(request);

                // Process the uploaded file items

                Iterator<FileItem> i = fileItems.iterator();

                while (i.hasNext()) {

                    FileItem fi = (FileItem) i.next();

                    if (!fi.isFormField()) {

                        // Get the uploaded file parameters

                        String fileName = fi.getName();

                        // Write the file

                        if (fileName.lastIndexOf("\\") >= 0) {

                            file = new File(filePath

                                + fileName.substring(fileName

                                        .lastIndexOf("\\")));

                        } else {

                            file = new File(filePath

                                + fileName.substring(fileName

                                        .lastIndexOf("\\") + 1));

                        }

                        fi.write(file);

                    } else {

                        key_values.put(fi.getFieldName(), fi.getString());

                    }

                }

            } catch (Exception ex) {

                System.out.println(ex);

            }

        }

        return key_values;

    }

}


查看完整回答
反对 回复 2019-05-21
  • 5 回答
  • 0 关注
  • 1055 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信