java文件上传功能

java文件上传功能
//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%>">

    <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">
    -->
  </head>

  <body>
    <form action="${pageContext.request.contextPath }/Upload3" method="post" enctype="multipart/form-data">  
      用户名;<input type="text" name="username"/><br/>  
      照 片:<input type="file" name="zhaoPian"/><br/>  
      <input type="submit" value="上传"/>  
    </form>  
  </body>
</html>

//servlet

package com.kero99.ygc.test;  
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;  
    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;

    public class Upload3 extends HttpServlet {       
        public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {         
            //设置编码响应到浏览器的格式
             response.setCharacterEncoding("UTF-8");
             response.setContentType("text/html;charset=UTF-8");
             //设置存的路径  存的文件需要在tomcat项目右键 Browse里找到/WEB-INF/files 
             String savepath=getServletContext().getRealPath("/WEB-INF/files");  
            //创建磁盘文件工厂 需要导入上传文件jar包 由工厂接受 解析器处理文件
            DiskFileItemFactory diskFileItemFactory=new DiskFileItemFactory();
            //创建文件解析器
            ServletFileUpload fileUpload=new ServletFileUpload(diskFileItemFactory);
            try {
                //设置上传文件的编码格式
                fileUpload.setHeaderEncoding("UTF-8");
                //接受请求 文件解析器解析请求 返回List<FileItem>接口 
                List<FileItem> list=fileUpload.parseRequest(request);
                //迭代 FileItem接口处理文件
            for(FileItem item:list){
                //如果fileitem中封装的是普通输入项的数据
                if(item.isFormField()){
                    //获取文本内容 eg: <input type="text" name="username"/> getFieldName为文本项内容=username
                    String name=item.getFieldName();
                    //获取文本内容 eg:<input type="text" name="username"/> getString=输出的文本
                    String value=item.getString("UTF-8"); 
                    //文本内容设置字符集为utf-8
                    String value1=new String(name.getBytes("iso8859-1"),"UTF-8");
                }else{//else 为上传的是文件
                    //获取上传文件的名字
                    String filename1=item.getName();

                    String filename=UUID.randomUUID().toString().replace("-","")+filename1;
                     int hCode = filename.hashCode();  
                        String hex = Integer.toHexString(hCode);  
                        File file = new File(savepath,hex.charAt(0)+"/"+hex.charAt(1)); 
                     if(!file.exists() && !file.isDirectory() &&!filename1.equals("") && filename1!=null && !filename1.trim().equals("")){
                         file.mkdirs();                  
                         String extension = FilenameUtils.getExtension(filename);
                            if(!("jsp".equals(extension)||"txt".equals(extension))){
                                File file1=new File(file,filename);
                                item.write(file1);
                                response.getWriter().print("success!");
                            }else{
                                response.getWriter().print("文件不能为jsp和exe类型,请从新上传...");
                            }
                     }else{
                         response.getWriter().print("不能是空文件");
                     }      
                  }
               }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }  
    }  

//文件上传重构版

package com.kero99.ygc.test;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

import com.sun.corba.se.spi.legacy.connection.GetEndPointInfoAgainException;



public class Upload extends HttpServlet{

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //设置响应浏览器格式
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String savapath=getServletContext().getRealPath("/WEB-INF/files");
        DiskFileItemFactory diskFileItemFactory=new DiskFileItemFactory();
        ServletFileUpload fileUpload=new ServletFileUpload(diskFileItemFactory);
        try {
            fileUpload.setHeaderEncoding("utf-8");
            List<FileItem> list=fileUpload.parseRequest(request);
            for(FileItem item:list){
                if(item.isFormField()){
                    String name=item.getFieldName();//获取文本项
                    String value=item.getString("utf-8");//获取文本内容 
                    String value1=new String(name.getBytes("iso8859-1"),"UTF-8");
                }else{//为上传的是文件         
                    String filename1=item.getName();
                    String filename=UUID.randomUUID().toString().replace("-","")+filename1;
                    //目录打散方法 a/b
                    String path=getFileChildPath(filename);         
                    File file=new File(savapath,path);
                    if(!file.exists() && !file.isDirectory()){
                        file.mkdirs();      
                        String extension=FilenameUtils.getExtension(filename);
                        if(!("jsp".equals(extension)||"txt".equals(extension))){
                            File file1=new File(file,filename);
                            item.write(file1);
                            response.getWriter().print("success");
                        }else{
                            response.getWriter().print("文件不能为jsp和exe类型");
                        }
                    }else{
                        response.getWriter().print("文件不能是空的");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    //目录打散
    public String getFileChildPath(String filename){
        int hCode=filename.hashCode();
        String hex=Integer.toHexString(hCode);
        String path=hex.charAt(0)+"/"+hex.charAt(1);
        return path;
    }

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
        super.destroy();
    }

    @Override
    public void init() throws ServletException {
        // TODO Auto-generated method stub
        super.init();
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

南归北隐

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值