Web应用服务器搭建,接受post文件上传方式并保存文件。

  文件测试客户端需要通过http的post方式向服务器上传文件,并且应用服务器需要保存这个文件。因此需要搭建一个局域网的服务器来接受,因为之前没有任何这方面的经验,走了不少弯路,因此记录下来自己做记录或者能给看到的人提供一点点帮助。

  我使用的是VMware player虚拟机工具搭建的Ubuntu 16.04版本的系统,首先需要安装Apache,在Ubuntu中可以使用sudo apt install apache2直接安装,然后可以通过sudo apt install tomcat8来安装。具体这些按照教程可以在网上很多例子,这里就不再赘述。//可以通过Tab键来看tomcat下有哪些版本。具体的Servlet知识可以参考 菜鸟教程

  当安装成功后可以在浏览器中打开127.0.0.1:8080来打开tomcat的默认界面。能正常打开即表明安装成功。

  tomcat的主页地址在/var/lib/tomcat8/webapps路径,我们可以在目录webapps下新建一个文件夹myapps来包含我们的Servlet程序。

  其中文件组织结构应该为:

  webapps

      --myapps

        --upload.html

        --temp :临时文件,注意文件的读写权限

        --uploadFile:上传文件的目录,注意文件的读写权限

        --WEB-INF

          --web.xml

          --lib //需要的库文件,点击下载 

            --commons-io-2.5.jar 

            --commons-fileupload-1.3.2.jar

          --classes

            --UploadServlet.class //编译生成的Servlet

  本次需要的文件主要有:

  WEB-INF 子目录中包含应用程序的部署描述符,名为 web.xml

  upload.html :文件上传页面,网页测试用。

  UploadServlet.java:上传处理Servlet程序

  upload.html文件如下:

<html> 
    <head>  <title>Servlet upload</title></head> 
    <body > 
      <form name="uploadForm" method="POST" 
        enctype="MULTIPART/FORM-DATA" 
        action="upload"> 
 
        User Name:<input type="text" name="username" size="30"/> 
        Upload File1:<input type="file" name="file1" size="30"/> 
        Upload File2:<input type="file" name="file2" size="30"/>   
        <input type="submit" name="submit" value="upload"> 
        <input type="reset" name="reset" value="reset"> 
      </form> 
    </body> 
</html>

UploadServlet.java文件:

import javax.servlet.*;  
import javax.servlet.http.*;  
import java.io.*;  
import java.util.*;  
import org.apache.commons.fileupload.*;  
import org.apache.commons.fileupload.servlet.*;  
import org.apache.commons.fileupload.disk.*;  
 
// Servlet 文件上传  
public class UploadServlet extends HttpServlet  
{  
    private String filePath;    // 文件存放目录  
    private String tempPath;    // 临时文件目录  
 
    // 初始化  
    public void init(ServletConfig config) throws ServletException  
    {  
        super.init(config);  
        // 从配置文件中获得初始化参数  
        filePath = config.getInitParameter("filepath");  
        tempPath = config.getInitParameter("temppath");  
 
        ServletContext context = getServletContext();  
 
        filePath = context.getRealPath(filePath);  
        tempPath = context.getRealPath(tempPath);  
        System.out.println("文件存放目录、临时文件目录准备完毕 ...");  
    }  
      
    // doPost  
    public void doPost(HttpServletRequest req, HttpServletResponse res)  
        throws IOException, ServletException  
    {  
        res.setContentType("text/plain;charset=gbk");  
        PrintWriter pw = res.getWriter();  
        try{  
            DiskFileItemFactory diskFactory = new DiskFileItemFactory();  
            // threshold 极限、临界值,即硬盘缓存 1M  
            diskFactory.setSizeThreshold(4 * 1024);  
            // repository 贮藏室,即临时文件目录  
            diskFactory.setRepository(new File(tempPath));  
          
            ServletFileUpload upload = new ServletFileUpload(diskFactory);  
            // 设置允许上传的最大文件大小 4M  
            upload.setSizeMax(4 * 1024 * 1024);  
            // 解析HTTP请求消息头  
            List fileItems = upload.parseRequest(req);  
            Iterator iter = fileItems.iterator();  
            while(iter.hasNext())  
            {  
                FileItem item = (FileItem)iter.next();  
                if(item.isFormField())  
                {  
                    System.out.println("处理表单内容 ...");  
                    processFormField(item, pw);  
                }else{  
                    System.out.println("处理上传的文件 ...");  
                    processUploadFile(item, pw);  
                }  
            }// end while()  
 
            pw.close();  
        }catch(Exception e){  
            System.out.println("使用 fileupload 包时发生异常 ...");  
            e.printStackTrace();  
        }// end try ... catch ...  
    }// end doPost()  
 
 
    // 处理表单内容  
    private void processFormField(FileItem item, PrintWriter pw)  
        throws Exception  
    {  
        String name = item.getFieldName();  
        String value = item.getString();          
        pw.println(name + " : " + value + "\r\n");  
    }  
      
    // 处理上传的文件  
    private void processUploadFile(FileItem item, PrintWriter pw)  
        throws Exception  
    {  
        // 此时的文件名包含了完整的路径,得注意加工一下  
        String filename = item.getName();         
        System.out.println("完整的文件名:" + filename);  
        int index = filename.lastIndexOf("\\");  
        filename = filename.substring(index + 1, filename.length());  
 
        long fileSize = item.getSize();  
 
        if("".equals(filename) && fileSize == 0)  
        {             
            System.out.println("文件名为空 ...");  
            return;  
        }  
 
        File uploadFile = new File(filePath + "/" + filename);  
        item.write(uploadFile);  
        pw.println(filename + " 文件保存完毕 ...");  
        pw.println("文件大小为 :" + fileSize + "\r\n");  
    }  
      
    // doGet  
    public void doGet(HttpServletRequest req, HttpServletResponse res)  
        throws IOException, ServletException  
    {  
        doPost(req, res);  
    }  
} 

web.xml文件:

<?xml version="1.0" encoding="gb2312"?> 
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" 
    version="2.4"> 
 
    <servlet> 
        <servlet-name>UploadServlet</servlet-name> 
        <servlet-class>UploadServlet</servlet-class> 
 
        <init-param> 
            <param-name>filepath</param-name> 
            <param-value>uploadFile</param-value> 
        </init-param> 
        <init-param> 
            <param-name>temppath</param-name> 
            <param-value>temp</param-value> 
        </init-param> 
    </servlet>      
 
    <servlet-mapping> 
        <servlet-name>UploadServlet</servlet-name> 
        <url-pattern>/upload</url-pattern> 
    </servlet-mapping> 
 
</web-app>

  因为只是一个小程序,所以没有建立工程使用IDE进行编译项目,直接通过命令行,javac命令来编译UploadServlet.java。编译这个文件的时候需要知道其包含的jar文件。这个程序中用到了commons-fileupload-1.3.2.jar还有servlet-api.jar 所以编译的时候需要指定javac -cp /usr/share/tomcat8/lib/servlet-api.jar:/var/lib/tomcat8/webapps/myapps/WEB-INF/lib/commons-fileupload-1.3.2.jar UploadServlet.java 进行编译。然后将生成的UploadServlet.class文件放到/var/lib/tomcat8/webapps/myapps/WEB-INF/classes/文件下。

当配置完成后可以在浏览器中访问:http://localhost:8080/myapps/upload.html 进行上传。

在http上传程序中可以通过http://localip:8080/myapps/upload来指定上传的文件url。在测试调试过程中可以查看tomcat的log文件。目录地址为/var/lib/tomcat8/logs/ 其中以当天日期命名了为log日志,控制台输出可以在当前目录使用 tail -f catalina.out 实时看到打印消息。 

本文主要参考

http://haolloyin.blog.51cto.com/1177454/368162/

http://www.runoob.com/servlet/servlet-file-uploading.html

posted @ 2017-04-27 19:25  Prefog  阅读(14578)  评论(1编辑  收藏  举报