欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

JavaWeb文件上传开发实例

时间:2020-10-23 16:01:31|栏目:JAVA代码|点击:

文件上传有SmartUpload、Apache的Commons fileupload.我们今天介绍Commons fileupload的用法。 

1.commons-fileupload-1.3.1.jar
下载地址:http://xiazai.jb51.net/201608/yuanma/javawebfileupload(jb51.net).rar

2.web.xml

<!-- 上传文件 服务器端 -->
 <servlet>
 <servlet-name>UploadServlet</servlet-name>
 <servlet-class>com.servlet.UploadServlet</servlet-class>
 <init-param>
 <param-name>filePath</param-name><!-- 文件存储路径 -->
 <param-value>F:\myeclipse\Workspaces\King\WebRoot\uploadfile\</param-value>
 </init-param>
 </servlet>
 
 <servlet-mapping>
 <servlet-name>UploadServlet</servlet-name>
 <url-pattern>/servlet/UploadServlet</url-pattern>
 </servlet-mapping>
3.UploadFile.jsp
<form action="servlet/UploadServlet" method="post" enctype="multipart/form-data">
  <div align="center">
   <fieldset style="width:80%">
    <legend>上传文件</legend><br/>
     <div align="left">上传文件1</div>
     <div align="left">
      <input type="file" name="file1"/>
     </div>
     <div align="left">上传文件2</div>
     <div align="left">
      <input type="file" name="file2"/>
     </div>
     <div>
      <div align='left'>上传文件说明1</div>
      <div align='left'><input type="text" name="description1"/></div>
     </div>
     <div>
      <div align='left'>上传文件说明2</div>
      <div align='left'><input type="text" name="description2"/></div>
     </div>
     <div>
      <div align='left'>
       <input type='submit' value="上传文件"/>
      </div>
     </div>
   </fieldset>
  </div>
 </form>

3.servlet

package com.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
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;

import sun.swing.FilePane;

public class UploadServlet extends HttpServlet {

 private String filePath;


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

 
 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

  response.setCharacterEncoding("UTF-8");
  response.getWriter().println("请以POST方式上传文件");
 }

 
 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  File file1 = null, file2 = null;
  String description1 = null, description2 = null;
  response.setCharacterEncoding("UTF-8");
  request.setCharacterEncoding("UTF-8");
  response.setContentType("text/html");
  PrintWriter out = response.getWriter();
  
  DiskFileUpload diskFileUpload = new DiskFileUpload();//解析request
  
  try {
   List<FileItem> fileList = diskFileUpload.parseRequest(request);//将结果放置到List中
   out.println("遍历所有的FileItem...</br>");
   this.log("遍历所有的FileItem...");
   for(FileItem fileItem : fileList){
    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>");
      description2 = 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>");
      //服务器端文件,放在uploadfile文件夹下
      file1 = new File(filePath,remoteFile.getName());
      file1.getParentFile().mkdirs();//创建文件夹路径
      file1.createNewFile();//创建新文件
      InputStream ins = fileItem.getInputStream();//FileItem的内容
      OutputStream ous = new FileOutputStream(file1);//输出到文件中
      try{
       byte[] buffer = new byte[1024];//字节缓存
       int len = 0;//实际缓存长度
       while((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("遍历到file2...</br>");
      out.println("客户端文件位置:"+remoteFile.getAbsolutePath()+"</br>");
      //服务器端文件,放在uploadfile文件夹下
      file2 = new File(filePath,remoteFile.getName());
      file2.getParentFile().mkdirs();//创建文件夹路径
      file2.createNewFile();//创建新文件
      InputStream ins = fileItem.getInputStream();//FileItem的内容
      OutputStream ous = new FileOutputStream(file2);//输出到文件中
      try{
       byte[] buffer = new byte[1024];//字节缓存
       int len = 0;//实际缓存长度
       while((len=ins.read(buffer)) > -1){//循环读入缓存
        ous.write(buffer,0,len);
       }
       out.println("已保存文件"+file2.getAbsolutePath()+"</br>");
      }
      finally{
       ous.close();
       ins.close();
      }
     }
    }
   }
   out.println("Request 解析完毕");
  } catch (FileUploadException e) {
   // TODO 自动生成的 catch 块
   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>");
   
   if(file1 != null){
    out.println("<div>");
    out.println(" <div align='left'>file1;</div>");
    out.println(" <div align='left'><a href='"+request.getContextPath()+
      file1.getName()+"'target=_blank>"+file1.getName()+"</a>");
    out.println("</div>");
    out.println("</div>");
   }
   if(file2 != null){
    out.println("<div>");
    out.println(" <div align='left'>file2;</div>");
    out.println(" <div align='left'><a href='"+request.getContextPath()+
      file2.getName()+"'target=_blank>"+file2.getName()+"</a>");
    out.println("</div>");
    out.println("</div>");
   }
   out.println("<div>");
   out.println(" <div align='left'>description1:</div>");
   out.println(" <div align='left'>");
   out.println(description1);
   out.println("</div>");
   out.println("</div>");
   
   out.println("<div>");
   out.println(" <div align='left'>description2:</div>");
   out.println(" <div align='left'>");
   out.println(description2);
   out.println("</div>");
   out.println("</div>");
   
   out.println(" </BODY>");
   out.println("</HTML>");
   out.flush();
   out.close();
  }
  
 }

 public String getServletInfo() {
  return "This is my default servlet created by Eclipse";
 }

 
 public void init() throws ServletException {
  // Put your code here
  filePath = getServletConfig().getInitParameter("filePath");
 }

}

上一篇:Java常见数据结构面试题(带答案)

栏    目:JAVA代码

下一篇:浅谈java中的TreeMap 排序与TreeSet 排序

本文标题:JavaWeb文件上传开发实例

本文地址:http://www.codeinn.net/misctech/15150.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有