servlet-上传文件

<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>

  <form action="${pageContext.request.contextPath}/shang" enctype="multipart/form-data" method="post">
    <input type="file" name="file">上传文件
    <input type="submit" value="提交">
  </form>
  $END$
  </body>
</html>

package com.xiang;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

public class shang extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//判断文件是不是普通文件
if(!ServletFileUpload.isMultipartContent(request))
{
    return; //终止方法 ,说明是普通文件,text等
}
//创建上传文件的保存路径,最好存在WEB-INF 安全 用户无法访问
        String uploadPath = this.getServletContext().getRealPath("WEB-INF/shang");
        File uploadFile =new File(uploadPath);
        if (!uploadFile.exists()) {
            uploadFile.mkdir(); //创建目录
        }
//缓存 临时文件
        String tmpPath = this.getServletContext().getRealPath("WEB-INF/tmp");
        File tmpFile =new File(tmpPath);
        if (!tmpFile.exists()) {
            tmpFile.mkdir(); //创建目录
        }
      //如果需要手写用request.getInputStream  推荐使用Common-fileupload

   //1.创建DiskFileItemFactory对象,处理文件上传路径或者大小限制
        DiskFileItemFactory factory=new DiskFileItemFactory();
//       factory.setSizeThreshold(1024*1024);//缓存区大小
        factory.setRepository(tmpFile);//临时目录的保存目录 需要一个file

        //2.获取 servletfileupload
      ServletFileUpload upload=new ServletFileUpload(factory);
      //监听文件上传进度
        upload.setProgressListener(new ProgressListener() {
            //pBytesRead 已经读取文件大小
            //pContentLength 文件大小
            @Override
            public void update(long pBytesRead, long pContentLength, int pItems) {
                System.out.println("总大小" +pContentLength+"已上传"+pBytesRead);
            }
        });
        //处理乱码
//        upload.setHeaderEncoding("UTF-8");
//        //设置单个文件最大值
//        upload.setFileSizeMax(1024*1024*10);
//        //设置总共能上传文件大小
//        upload.setSizeMax(1024*1024*10);


        //3.处理文件上传  把前端请求解析,封装成一个fileitem对象

        //                       文件处理

        System.out.println(11111);
        List<FileItem> fileItems=null;
        try {
            fileItems=upload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        System.out.println(2222);
        System.out.println(fileItems.get(0).getFieldName());
        //判断是否是普通的还是文件的表单
        for (FileItem f :
                fileItems) {
            if (f.isFormField())
            {
String name=f.getFieldName();//获取前端名
String value =f.getString("utf-8");//处理乱码
                System.out.println(name+":"+value);
            }
            else {

                System.out.println(333);
                String name=f.getFieldName();//获取前端名
                if (name.trim().equals("")||name==null)
                {//判断文件名是否合法
                    continue;
                }
                //获取上传文件名 /images/girl/paojie.png
                //文件名
                String fileName=name.substring(name.lastIndexOf("/")+1);
                //后缀名
                String fileExtname=name.substring(name.lastIndexOf(".")+1);

                //        存放地址
                 //用uuid实现文件名唯一
                UUID uuid = UUID.randomUUID();
                String realpath=uploadPath+"/"+uuid;
                File realPathFile=new File(realpath);
                if (!realPathFile.exists())
                realPathFile.mkdir();

            //              文件传输
               //获取上传流
                InputStream inputStream=f.getInputStream();

                System.out.println(inputStream==null);
                //创建输出流
                FileOutputStream fos=new FileOutputStream(realpath+"/"+name);

                byte[] buff=new byte[1024*1024];
                int len=0;
                while ((len=inputStream.read())>0)
                {
                    fos.write(buff,0,len);
                }
                fos.close();
                inputStream.close();
                String msg="文件上传成功";
                System.out.println(msg);
                f.delete();//删除临时文件

            }
        }

    }


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值