文件上传到服务器端口

来源:互联网 发布:网站统计分析系统源码 编辑:程序博客网 时间:2024/06/05 10:06

1.1 上传文件需要在form表单里,需要注意下面两点。
(1)method必须设置为:post
(2)enctype="multipart/form-data"(如果这样设置,传递过去的参数,就不可以通过getParameter来获取)
这样才能保证文件的二进制字节流可以在报文体中发过去
<form method="post" enctype="multipart/form-data"/> 
<form>
1.2
文件上传的代码
 package com.rupeng.web7;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
import java.util.Calendar;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;




public class UploadServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
this.doPost(req, resp);
}




@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException{
req.setCharacterEncoding("utf-8");//设置成功之后,才可以避免文件名字乱码的情况。
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=UTF-8");
//一旦使用enctype="multipart/form-data"。不能适用getParameter来获取参数的取值
// 无论是type="file",还是普通的表单域(input,select,textarea),都是一项对应一个DiskFileItem。
//对于普通的表单域,getFiledName()。获得是表单域的名字。getString(),获得的是取值
//对于type="file",getFiledName()。获得的是表单域的名字,getName(),获得是用户选择的文件名字


//经过实验得知,如果表单是 enctype="multipart/form-data"。
//请求的contentType就是:Content-Type:multipart/form-data; boundary=---WebKitFormBoundaryPVf6nNjSf8gm7HIq
//如果表单不是 enctype="multipart/form-data"。
//请求的contentType就是:application/x-www-form-urlencoded


//通过Request的contentType,就可以知道怎么提交的
String action = null;//String类型的变量 =null也相当于被初始化了
//if(req.getContentType().startsWith("multipart/form-data")){


//不同的表单,
List<DiskFileItem> files = null;
if(ServletFileUpload.isMultipartContent(req)){
String tempFullPath = this.getServletContext().getRealPath("/WEB-INF/temp");//this指的是当前对象
//也可以写成//String tempFullPath = req.getSession().getServletContext().getRealPath("/WEB-INF/temp");
System.out.println(tempFullPath);
File fileTemp = new File(tempFullPath);//把二进制文件流,上传的临时文件夹
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(2*1024,fileTemp);//磁盘文件工厂
ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory);
PrintWriter out = resp.getWriter();
try {
files = upload.parseRequest(req);//req对象传进来
DiskFileItem DiskFileItem =RPUtils.findDiskFileItem(files, "action");
if(DiskFileItem!=null){
action = DiskFileItem.getString();
}//到此结束,得到action的取值
/* 遍历files。然后把文件的二进制字节流显示到浏览器上
for(DiskFileItem file:files){
out.print("name="+file.getName()+",FileName="+file.getFieldName()
+",String ="+file.getString()+"<br/>");
}
DiskFileItem file =files.get(0);
resp.getWriter().println(file.getContentType());//getContentType 。得到文件的类型
resp.getWriter().println(file.getName());//getName() 得到文件的文件名称
*/
} catch (FileUploadException e) {
 resp.getWriter().print("文件上传错误"+e.getMessage());
}//从请求中解析出上传的文件内容。
}else{
//System.out.println("s");
action = req.getParameter("action");

if(RPUtils.isNullOrEmpty(action)){
req.getRequestDispatcher("/Upload1.jsp").forward(req, resp);
}else if(action.equals("uploadSubmit")){
/*  一旦执行一个parseRequest之后,request的流的指针,就指向最后了,所以一般不 重复适用parseRequest
String tempFullPath = this.getServletContext().getRealPath("/WEB-INF/temp");//this指的是当前对象
//也可以写成//String tempFullPath = req.getSession().getServletContext().getRealPath("/WEB-INF/temp");
File fileTemp = new File(tempFullPath);//把二进制文件流,上传的临时文件夹
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(4*1024*1024, fileTemp);//磁盘文件工
ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory);


//List<DiskFileItem> files = upload.parseRequest(req);//此时指针已经位于
//inputStream的结尾了
* */
   PrintWriter out = resp.getWriter();
DiskFileItem f1=RPUtils.findDiskFileItem(files, "f1");//之前的upload已经parseRequest组件了
//所以可以直接用之前的files即可,
String fileExt = FilenameUtils.getExtension(f1.getName());
if(!fileExt.equalsIgnoreCase("zip")&&!fileExt.equalsIgnoreCase("rar")&&!fileExt.equalsIgnoreCase("jpg")&&!fileExt.equalsIgnoreCase("png")&&!fileExt.equalsIgnoreCase("zip")){
resp.getWriter().print("不允许上传.zip,.rar,.jpg,.png,.zip 以外的格式的文件");
}else{
//eclispe中的upload(文件夹)是开发的时候用的文件夹
//tomcat运行的时候,其实操作的是.me_cat\webapps\下的这个文件夹
// String uploadFullPath = this.getServletContext().getRealPath("/upload/"+f1.getName());//上传文件的文件夹全路径


/**
* 获得当前时间,拿到年月日
*/
Date now =new Date(System.currentTimeMillis());//当前的时间对象,获得当前时间
Calendar calendar = Calendar.getInstance();


int year = calendar.get(Calendar.YEAR);
int month =calendar.get(Calendar.MONTH)+1;//月份是从0开始的所以 要+1
int day = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println(now+"------------");
//以年月日为文件夹
String uploadFullPath = this.getServletContext().getRealPath("/upload/"+year+"/"+month+"/"+day+"/"+f1.getName());
File file= new File(uploadFullPath);//拿到文件对象
File parentFile = file.getParentFile();//拿到文件,所在的文件夹
                //判断文件夹是否存在
if(!parentFile.exists()){
parentFile.mkdirs();//文件夹的父级目录不存在,也会统统创建出来,但是.mkdir。必须附近目录存在才可以。mkdirs会把
//如果文件夹不存在,
}
System.out.println(uploadFullPath);
FileOutputStream fos = new FileOutputStream(uploadFullPath);//没有文件,可以创建文件,没有文件夹,就不可以了
//f1.getInputStream()
try{
IOUtils.copy(f1.getInputStream(), fos);//,拿到文件的内容.把上传文件的内容拷贝到输出的文件流中
}finally{
//f1.getInputStream不需要我们,关,框架,会把流关掉。
IOUtils.closeQuietly(fos);
}
resp.getWriter().print("文件上传成功 ");
DiskFileItem f2 = RPUtils.findDiskFileItem(files,"f2");
if(f2.getSize()<=0){//小于0成立,就说明没有上传文件。利用getSize来判断用户是否选择文件。即便用户没选择文件,f2 !=null.只是getsize()==0。
//ajax是不可以上传文件的!上传文本信息
resp.getWriter().print("用户没有选择f2");
}else{
resp.getWriter().print("f2文件名是"+f2.getName());
}
}
}
/*
DiskFileItem file =files.get(0);
resp.getWriter().println(file.getContentType());//getContentType 。得到文件的类型
resp.getWriter().println(file.getName());//getName() 得到文件的文件名称
*/
}
}