欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

javaweb实现文件上传示例代码

程序员文章站 2024-03-02 18:34:58
本文实例为大家分享了javaweb文件下载的具体实现代码,供大家参考,具体内容如下 文件上传示例 注意:jsp页面编码为"utf-8" 文件上传的必要条件 1.fo...

本文实例为大家分享了javaweb文件下载的具体实现代码,供大家参考,具体内容如下

文件上传示例

注意:jsp页面编码为"utf-8"

文件上传的必要条件

1.form表单,必须为post方式提交

2.enctype="multipart/form-data"

3.必须有<input type="file" />

前端jsp页面

<%@ page language="java" import="java.util.*" pageencoding="utf-8"%>
<%
string path = request.getcontextpath();
string basepath = request.getscheme()+"://"+request.getservername()+":"+request.getserverport()+path+"/";
%>

<!doctype html public "-//w3c//dtd html 4.01 transitional//en">
<html>
 <head>
 <base href="<%=basepath%>" rel="external nofollow" >
 
 <title>my jsp 'index.jsp' starting page</title>
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0"> 
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="this is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css" rel="external nofollow" >
 -->
 </head>
 <script type="text/javascript">
  function addfile(){
   var div1=document.getelementbyid("div1");
   div1.innerhtml+="<div><input type='file' /><input type='button' value='删除' onclick='deletefile(this)' /> <br/></div>";
  
  }
  function deletefile(div){
   //他的爷爷删除他的爸爸
   div.parentnode.parentnode.removechild(div.parentnode);
  
  }
 </script>
 <body>
  <form action="${pagecontext.request.contextpath }/servlet/uploadservlet" method="post" enctype="multipart/form-data">
  文件的描述:<input type="text" name ="description" /><br/>
  <div id="div1">
   <div>
   <input type="file" name ="file" /><input type="button" value="添加" onclick="addfile()" /><br/>
   </div>   
  </div> 
   <input type="submit" />
  </form>
 </body>
</html>

实现文件上传的servlet

package com.learning.servlet;

import java.io.file;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.io.inputstream;
import java.io.unsupportedencodingexception;
import java.text.simpledateformat;
import java.util.date;
import java.util.list;
import java.util.uuid;

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 org.apache.commons.fileupload.fileitem;
import org.apache.commons.fileupload.fileuploadexception;
import org.apache.commons.fileupload.disk.diskfileitemfactory;
import org.apache.commons.fileupload.servlet.servletfileupload;
import org.apache.commons.io.filenameutils;

/**
 * servlet implementation class uploadservlet
 */
@webservlet("/servlet/uploadservlet")
public class uploadservlet extends httpservlet {
 private static final long serialversionuid = 1l;

 /**
  * @see httpservlet#doget(httpservletrequest request, httpservletresponse response)
  */
 protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
  doget(request, response);
 }

 /**
  * @see httpservlet#dopost(httpservletrequest request, httpservletresponse response)
  */
 protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
   
  
  //文件上传
  //判断是否支持文件上传
  boolean ismultipartcontent = servletfileupload
    .ismultipartcontent(request);
  if (!ismultipartcontent) {
   throw new runtimeexception("不支持");
  }
  
  // 创建一个diskfileitemfactory工厂类
  diskfileitemfactory diskfileitemfactory=new diskfileitemfactory();
  // 创建一个servletfileupload核心对象
  servletfileupload fileupload=new servletfileupload(diskfileitemfactory);
  //设置中文乱码
  fileupload.setheaderencoding("utf-8");
  //设置一个文件大小
  fileupload.setfilesizemax(1024*1024*3); //大小为3m
  //设置总文件大小
  //fileupload.setsizemax(1024*1024*10);//大小为10m
  
  try {
   //fileload解析request请求,返回list<fileitem>集合
   list<fileitem> fileitems = fileupload.parserequest(request);
   for (fileitem fileitem : fileitems) {
    if (fileitem.isformfield()) {
     //是文本域 (处理文本域的函数)
     processformfield(fileitem);
    }else {
     //文件域 (处理文件域的函数)
     processuploadfield1(fileitem);
    }
   }
   
  } catch (fileuploadexception e) {
   e.printstacktrace();
  }
  
  
 }

 /**
  * @param fileitem
  * 
  */
 private void processuploadfield1(fileitem fileitem) {
  
  try {
   //获得文件读取流
   inputstream inputstream = fileitem.getinputstream();
   
   //获得文件名
   string filename = fileitem.getname();
   
   //对文件名处理
   if (filename!=null) {
    filename.substring(filename.lastindexof(file.separator)+1);
    
   }else {
    throw new runtimeexception("文件名不存在");
   }
   
   //对文件名重复处理
//   filename=new string(filename.getbytes("iso-8859-1"),"utf-8");
   filename=uuid.randomuuid()+"_"+filename;
   
   //日期分类
   simpledateformat simpledateformat=new simpledateformat("yyyy-mm-dd");
   string date = simpledateformat.format(new date());
   //创建目录
   file parent=new file(this.getservletcontext().getrealpath("/web-inf/upload/"+date));
   if (!parent.exists()) {
    parent.mkdirs();
   }
   
   //上传文件
   fileitem.write(new file(parent, filename));
   //删除临时文件(如果上传文件过大,会产生.tmp的临时文件)
   fileitem.delete();
   
  } catch (ioexception e) {
   system.out.println("上传失败");
   e.printstacktrace();
  } catch (exception e) {
   
  }
  
  
  
 }

 /**
  * @param fileitem
  */
 //文件域
 private void processuploadfield(fileitem fileitem) {
   
  try {
   //获得文件输入流
   inputstream inputstream = fileitem.getinputstream();
   
   //获得是文件名字
   string filename = fileitem.getname();
   //对文件名字处理
   if (filename!=null) {
//    filename.substring(filename.lastindexof(file.separator)+1);
    filename = filenameutils.getname(filename);
   }
   
   //获得路径,创建目录来存放文件
   string realpath = this.getservletcontext().getrealpath("/web-inf/load");
   
   file storedirectory=new file(realpath);//既代表文件又代表目录
   //创建指定目录
   if (!storedirectory.exists()) {
    storedirectory.mkdirs();
   }
   //防止文件名一样
   filename=uuid.randomuuid()+"_"+filename;
   //目录打散 防止同一目录文件下文件太多,不好查找
   
   //按照日期分类存放上传的文件
   //storedirectory = makechilddirectory(storedirectory);
   
   //多级目录存放上传的文件
   storedirectory = makechilddirectory(storedirectory,filename);
   
   fileoutputstream fileoutputstream=new fileoutputstream(new file(storedirectory, filename));
   //读取文件,输出到指定的目录中
   int len=1;
   byte[] b=new byte[1024];
   while((len=inputstream.read(b))!=-1){
    fileoutputstream.write(b, 0, len);
   }
   //关闭流
   fileoutputstream.close();
   inputstream.close(); 
   
  } catch (ioexception e) {
   e.printstacktrace();
  } 
 }
 //按照日期来分类
 private file makechilddirectory(file storedirectory) {
  simpledateformat simpledateformat=new simpledateformat("yyyy-mm-dd");
  string date = simpledateformat.format(new date());
  //创建目录
  file childdirectory=new file(storedirectory, date);
  if (!childdirectory.exists()) {
   childdirectory.mkdirs();
  }
  return childdirectory;
 } 
 //多级目录
 private file makechilddirectory(file storedirectory, string filename) {
  filename=filename.replaceall("-", ""); 
  file childdirectory =new file(storedirectory, filename.charat(0)+file.separator+filename.charat(1));
  if (!childdirectory.exists()) {
   childdirectory.mkdirs();  
  }
  return childdirectory;
 }
 //文本域
 private void processformfield(fileitem fileitem) {
  //对于文本域的中文乱码,可以用new string()方式解决
   try {
    string fieldname = fileitem.getfieldname();//表单中字段名name,如description
    string fieldvalue = fileitem.getstring("utf-8");//description中value
//    fieldvalue=new string(fieldvalue.getbytes("iso-8859-1"),"utf-8");
    system.out.println(fieldname +":"+fieldvalue);
   } catch (unsupportedencodingexception e) {
    // todo auto-generated catch block
    e.printstacktrace();
   }
   
 }

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。