上传一个简单文件

**

上传文件

**

(1)加入相应的包
在这里插入图片描述
(2)创建一个简单页面

<body>
<form method="post" action="#" id="uploadForm" enctype="multipart/form-data">
    用户名: <input type="text" name="userName"><br>
    头像:<input type="file" name="userPic"><br>
    <input type="button" id="uploadBtn" value="提交"><br>
</form>
</body>

<script  src="lib/jquery/jquery-1.9.1.min.js"></script>
<script>
    $("#uploadBtn").click(function () {
        /**
         * $("#uploadForm") 是一个JQuery对象
         * $("#uploadForm")[0] 将JQuery对象转成DOM元素
         * @type {FormData}
         */
        var formData = new FormData($("#uploadForm")[0]);
        $.ajax({
            url:"updateServlet",
            type:"POST",
            data:formData,
            async:false,
            cache:false,
            contentType:false,
            processData:false,
            success:function (result) {
                console.log(result);
            },
            error:function (error) {
                console.log("error:"+error);
            }
        })
    })
</script>

(3)创建一个servlert

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    /**
     * 将上传的文件img目录下,并且使用时间戳命名,
     *  上传文件,文件名需要修改:保证唯一,不重复
     */
    //配置上传的参数
    DiskFileItemFactory factory=new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    //设置字符集
    upload.setHeaderEncoding("utf-8");
    //解析请求的内容,提取文件数据
    List fileList=null;
    try {
        fileList =upload.parseRequest(request);
    } catch (FileUploadException e) {
        e.printStackTrace();
    }
    Iterator<FileItem> iterator =fileList.iterator();
    //迭代表单数据
    while (iterator.hasNext())
    {
        FileItem item=iterator.next();
        //处理不是文件的字段
        if (!item.isFormField())
        {

            String filedName =item.getFieldName();//字段的
            //定义上传文件的存放路径
            String fileName=item.getName();//上传的文档名
            String suffix=fileName.substring(fileName.lastIndexOf("."));//上传的文档的后缀
            long id=new Date().getTime();//时间戳,用来保存文件的文件名
            //需要准备一个文件夹picture最好里面存在一个文件,空文件夹容易不放到缓存中,以至于到这一步是找不到该文件夹
            String savePath=this.getServletContext().getRealPath("picture");
            String fileUrl =String.format("%s/%d%s",savePath,id,suffix);//定义上传文件的完整路径
            System.out.println(fileUrl);
            File file=new File(fileUrl);
            try {
                item.write(file);
            } catch (Exception e) {
                e.printStackTrace();

            }

        }else {
            String fieldName=item.getFieldName();
            String value=item.getString();
            System.out.println(fieldName+"->"+value);
        }
    }

}

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值