美文网首页
文件上传(java)

文件上传(java)

作者: Admin_Yan | 来源:发表于2019-05-12 13:36 被阅读0次

      最近看了一本书上的代码,代码的主要功能是实现文件的上传。但是,当我运行代码的时候竟然报错了。(我用的IDEA)。有错就解决吧。以下是我遇到的几个错误。

    废话不多说先附上源代码。

    UploadServlet.java

    package com;
    
    import java.io.File;
    import java.io.IOException;
    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 javax.servlet.http.Part;
    import java.lang.String;
    
    import java.io.PrintWriter;
    import javax.servlet.annotation.MultipartConfig;
    
    import org.apache.catalina.core.ApplicationPart;
    
    @WebServlet("/UploadServlet")
    @MultipartConfig(location = "d:/temp")                                  //D盘手动创建temp文件夹
    public class UploadServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            String path = this.getServletContext().getRealPath("/");        //获取服务器地址
            Part p = request.getPart("file1");                              //获取用户上传的文件
            if (p.getContentType().contains("image")){                      //仅处理上传的图片文件
                ApplicationPart ap =(ApplicationPart)p;  
            String fname1 = ap.getFilename();                               //获取上传文件名
                int path_idx = fname1.lastIndexOf("\\") + 1;                //对上传文件名进行截取
                String fname2 = fname1.substring(path_idx, fname1.length());
                File file = new File(path + "/upload/" + fname2);           //写入web根目录下的upload文件夹中
                out.write("文件上传成功");
            }
            else{
                out.write("请选择图片文件!!!");
            }
        }
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
        }
    }
    
    

    index.jsp

    <%--
      Created by IntelliJ IDEA.
      User: Chenaniah Gu
      Date: 2019/5/11
      Time: 21:55
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>文件上传</title>
    </head>
    <body>
    <form action="UploadServlet" enctype="multipart/form-data" method="post">
        选择文件<input type="file" name="file1" id="file1"/>
        <input type="submit" name="upload" value="上传"/>
    </form>
    </body>
    </html>
    
    

    这是某本书的代码,可能环境配置和书上的一样,不会出错,但是往往都是环境不一样。下面来看几个错误。

    1. import org.apache.catalina.core.ApplicationPart;报错

      很明显,这个报错就是因为找不到这个包,那么这个包在哪呢?其实它就在Tomcat根目录中的lib文件夹中,这个包名叫做catalina.jar。导入这个包文件就OK啦,若导入后不行,那就重启IDEA。

    2. getFilename()方法找不到

      分析一下,这个getFilename()方法是哪的?java自带包定义的?,抱歉没搜到。既然不是自带包,你也没定义,那就很有可能是引入包中的方法,再细细分析,可以发现是ap调用了它,ap的类型是什么呢?ApplicationPart。打开ApplicationPart方法,如下图所示。

    1.JPG

      我用的是Tomcat9.0,打开ApplicationPart.class

    //
    // Source code recreated from a .class file by IntelliJ IDEA
    // (powered by Fernflower decompiler)
    //
    
    package org.apache.catalina.core;
    
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.UnsupportedEncodingException;
    import java.util.Collection;
    import java.util.Collections;
    import java.util.Iterator;
    import java.util.LinkedHashSet;
    import java.util.Locale;
    import java.util.Map;
    import javax.servlet.http.Part;
    import org.apache.tomcat.util.http.fileupload.FileItem;
    import org.apache.tomcat.util.http.fileupload.ParameterParser;
    import org.apache.tomcat.util.http.fileupload.disk.DiskFileItem;
    import org.apache.tomcat.util.http.parser.HttpParser;
    
    public class ApplicationPart implements Part {
        private final FileItem fileItem;
        private final File location;
    
        public ApplicationPart(FileItem fileItem, File location) {
            this.fileItem = fileItem;
            this.location = location;
        }
    
        public void delete() throws IOException {
            this.fileItem.delete();
        }
    
        public String getContentType() {
            return this.fileItem.getContentType();
        }
    
        public String getHeader(String name) {
            return this.fileItem instanceof DiskFileItem ? this.fileItem.getHeaders().getHeader(name) : null;
        }
    
        public Collection<String> getHeaderNames() {
            if (!(this.fileItem instanceof DiskFileItem)) {
                return Collections.emptyList();
            } else {
                LinkedHashSet<String> headerNames = new LinkedHashSet();
                Iterator iter = this.fileItem.getHeaders().getHeaderNames();
    
                while(iter.hasNext()) {
                    headerNames.add(iter.next());
                }
    
                return headerNames;
            }
        }
    
        public Collection<String> getHeaders(String name) {
            if (!(this.fileItem instanceof DiskFileItem)) {
                return Collections.emptyList();
            } else {
                LinkedHashSet<String> headers = new LinkedHashSet();
                Iterator iter = this.fileItem.getHeaders().getHeaders(name);
    
                while(iter.hasNext()) {
                    headers.add(iter.next());
                }
    
                return headers;
            }
        }
    
        public InputStream getInputStream() throws IOException {
            return this.fileItem.getInputStream();
        }
    
        public String getName() {
            return this.fileItem.getFieldName();
        }
    
        public long getSize() {
            return this.fileItem.getSize();
        }
    
        public void write(String fileName) throws IOException {
            File file = new File(fileName);
            if (!file.isAbsolute()) {
                file = new File(this.location, fileName);
            }
    
            try {
                this.fileItem.write(file);
            } catch (Exception var4) {
                throw new IOException(var4);
            }
        }
    
        public String getString(String encoding) throws UnsupportedEncodingException {
            return this.fileItem.getString(encoding);
        }
    
        public String getSubmittedFileName() {
            String fileName = null;
            String cd = this.getHeader("Content-Disposition");
            if (cd != null) {
                String cdl = cd.toLowerCase(Locale.ENGLISH);
                if (cdl.startsWith("form-data") || cdl.startsWith("attachment")) {
                    ParameterParser paramParser = new ParameterParser();
                    paramParser.setLowerCaseNames(true);
                    Map<String, String> params = paramParser.parse(cd, ';');
                    if (params.containsKey("filename")) {
                        fileName = (String)params.get("filename");
                        if (fileName != null) {
                            if (fileName.indexOf(92) > -1) {
                                fileName = HttpParser.unquote(fileName.trim());
                            } else {
                                fileName = fileName.trim();
                            }
                        } else {
                            fileName = "";
                        }
                    }
                }
            }
    
            return fileName;
        }
    }
    
    

      你会发现根本没有getFilename()这个方法。是不是有一种被骗的感觉?
    怎么解决呢?两种方法,首先你可以自己写一个这样的方法,其次就是用java中的File类。

    修改后的代码如下 UploadServlet.java

    package com;
    
    import java.io.File;
    import java.io.IOException;
    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 javax.servlet.http.Part;
    import java.lang.String;
    
    import java.io.PrintWriter;
    import javax.servlet.annotation.MultipartConfig;
    
    import org.apache.catalina.core.ApplicationPart;
    
    @WebServlet("/UploadServlet")
    @MultipartConfig(location = "d:/temp")                                  //D盘手动创建temp文件夹
    public class UploadServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            String path = this.getServletContext().getRealPath("/");        //获取服务器地址
    
            System.out.println("服务器地址是"+path);
    
            Part p = request.getPart("file1");                              //获取用户上传的文件
            if (p.getContentType().contains("image")){                      //仅处理上传的图片文件
                ApplicationPart ap =(ApplicationPart)p;
                String filename = ap.getSubmittedFileName();                //获取文件名
                System.out.println(filename);
                File file = new File(path + "/upload/" + filename);
                System.out.println("file.getPath()的值是"+file.getPath());
                p.write(file.getPath());                                    //写入web根目录下的upload文件夹中
                out.write("文件上传成功");
            }
            else{
                out.write("请选择图片文件!!!");
            }
        }
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
        }
    }
    
    

    最后附上一张成功运行的截图

    2.JPG

    相关文章

      网友评论

          本文标题:文件上传(java)

          本文链接:https://www.haomeiwen.com/subject/dkkcaqtx.html