上传文件

这个我有点不是很明白原理,借作api抄抄书上的代码

package servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;

public class UploadServlet extends HttpServlet {

    /**
     * Constructor of the object.
     */
    public UploadServlet() {
        super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">");
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
        out.println("  <BODY>");
        out.print("    This is ");
        out.print(this.getClass());
        out.println(", using the GET method");
        out.println("  </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        File file1=null,file2=null;
        String description1=null,description2=null;
        PrintWriter out = response.getWriter();
        DiskFileUpload diskFileUpload=new DiskFileUpload();
        try{
            List<FileItem> list=diskFileUpload.parseRequest(request);
            out.println("遍历所有的FileItem...<br/>");
            for(FileItem fileItem:list){
                if(fileItem.isFormField()){
                    if("description1".equals(fileItem.getFieldName())){
                        out.println("遍历到description1...<br/>");
                        description1=new String(fileItem.getString().getBytes(),"UTF-8");
                    }
                    if("description2".equals(fileItem.getFieldName())){
                        out.println("遍历到description2...<br/>");
                        description1=new String(fileItem.getString().getBytes(),"UTF-8");
                    }
                }
                else{
                    if("file1".equals(fileItem.getFieldName())){
                        File remoteFile=new File(new String(fileItem.getName().getBytes(),"UTF-8"));
                        out.println("便利到file1...<br/>");
                        out.println("客户端文件位置"+remoteFile.getAbsolutePath()+"<br/>");
                        file1=new File(this.getServletContext().getRealPath("attachment"),remoteFile.getName());
                        file1.getParentFile().mkdirs();
                        file1.createNewFile();
                        InputStream ins=fileItem.getInputStream();
                        OutputStream ous=new FileOutputStream(file1);
                        try{
                            byte[]buffer =new byte[1024];
                            int len=0;
                            for(;(len=ins.read(buffer))>-1;){
                                ous.write(buffer,0,len);
                            }
                            out.println("已经保存文件"+file1.getAbsolutePath()+"<br/>");
                            
                        }finally{
                            ous.close();
                            ins.close();
                        }
                    }
                    if("file2".equals(fileItem.getFieldName())){
                        File remoteFile=new File(new String(fileItem.getName().getBytes(),"UTF-8"));
                        out.println("便利到fil2...<br/>");
                        out.println("客户端文件位置"+remoteFile.getAbsolutePath()+"<br/>");
                        file1=new File(this.getServletContext().getRealPath("attachment"),remoteFile.getName());
                        file1.getParentFile().mkdirs();
                        file1.createNewFile();
                        InputStream ins=fileItem.getInputStream();
                        OutputStream ous=new FileOutputStream(file1);
                        try{
                            byte[]buffer =new byte[1024];
                            int len=0;
                            for(;(len=ins.read(buffer))>-1;){
                                ous.write(buffer,0,len);
                            }
                            out.println("已经保存文件"+file1.getAbsolutePath()+"<br/>");
                            
                        }finally{
                            ous.close();
                            ins.close();
                        }
                    }
                }
            }
            out.println("request 解析完毕");
        }catch(FileUploadException e){}
        if(file1!=null){
            //
        }
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
    }

}
View Code
<html>
    <head>
        <meta charset="UTF-8"/>
        <title>
        </title>
    </head>
    <body>
        <form action="servlet/UploadServlet" method="post" enctype="multipart/form-data">
            <div align="center"><br/>
                <fieldset style="80%">
                    <legend>上传文件</legend><br />
                    <div class='line'>
                        <div align="left" class='leftDiv'>上传文件一</div>                        
                        <div align='left' class='rightDiv'>
                            <input type="file" name="file1" class="text">
                        </div>
                    </div>
                    <div class='line'>
                        <div align="left" class='leftDiv'>上传文件二</div>                        
                        <div align='left' class='rightDiv'>
                            <input type="file" name="file1" class="text">
                        </div>
                    </div>
                    <div class='line'>
                        <div align="left" class='leftDiv'>上传文件说明一</div>                        
                        <div align='left' class='rightDiv'>
                            <input type="text" name="description1" class="text">
                        </div>
                    </div>
                    <div class='line'>
                        <div align="left" class='leftDiv'>上传文件说二</div>                        
                        <div align='left' class='rightDiv'>
                            <input type="text" name="description2" class="text">
                        </div>
                    </div>
                    <div class='line'>
                        <div align="left" class='leftDiv'></div>                    
                        <div align='left' class='rightDiv'><br />
                            <input type="submit" value="上传文件" class="button">
                        </div>
                    </div>
                </fieldset>            
            </div>
        </form>    
    </body>
</html>
View Code
原文地址:https://www.cnblogs.com/vhyc/p/6290933.html