编程语言
首页 > 编程语言> > JavaWeb servlet文件上传

JavaWeb servlet文件上传

作者:互联网

servlet

 HashMap map=new HashMap();
            //上传
            boolean isMultipart= ServletFileUpload.isMultipartContent(req);
            if (isMultipart){//判断前台的from是否有multipart属性
                FileItemFactory factory=new DiskFileItemFactory();
                ServletFileUpload upload=new ServletFileUpload(factory);
                try {
                    //通过parseRequest解析from中的所有请求字段,并保存到items集合中(即前台传递的file就保存在了items)
                    List<FileItem> items= upload.parseRequest(req);
                    Iterator<FileItem> iter= items.iterator();
                    while (iter.hasNext()){
                        FileItem item= iter.next();
                        //判断是表单字段还是文件字段
                        if (!item.isFormField()){
                            //文件上传
	           //文件名
  	           String fieldName = item.getFieldName();
                            //文件名getName() 获取文件字段的值
                            String fileName= item.getName();
                          
                            map.put(fieldName,fileName);
                            //文件的内容,并上传
                            //定义文件路径,指定上传的位置(服务器路径)
                            String upload1 = req.getServletContext().getRealPath("upload");
                            String[] outs = upload1.split("out");
                            String homePath=outs[0]+"web\\img\\upload";
                            File file1=new File(homePath,fileName);
                            item.write(file1);//上传
                        }else {
	            //普通字段
                            String fieldName = item.getFieldName();
                            String val = item.getString("utf-8");
                            map.put(fieldName,val);
                        }
                    }
                } catch (FileUploadException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

Html

<form method="post" action="" enctype="multipart/form-data">
	<input type="file" name="fileImg">
	<input type="text" name="username">
</form>

标签:JavaWeb,servlet,upload,item,fieldName,new,上传,String
来源: https://blog.csdn.net/lay2002/article/details/123419616