上传文件,保存到服务器,并将文件名存入数据库,及后续在前端调用文件

HTML代码

<form method="post" action="lai?action=insert" name="myfrm" id="myfrm" enctype="multipart/form-data"> 
//上传文件时必须使用enctype="multipart/form-data"
	<input style="font-size:3em" type="text" name="title" id="title" value="" placeholder="请填写事件标题" class="fl" />
	<input style="font-size:3em" type="text" name="place" id="place" value="" placeholder="请填写事件地点" class="fl" />
	<input type="file"  name="file" id="file">
	<input type="submit" value="Submit" />
</form>			

java代码

public void insert(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException,Exception{
		FileItemFactory factory = new DiskFileItemFactory();
		 // 创建文件上传处理器
        ServletFileUpload upload = new ServletFileUpload(factory);
        String fileName = null;

        // 开始解析请求信息
        java.util.List<FileItem>  items = null;
        try {
            items = upload.parseRequest(request);
        }
        catch (FileUploadException e) {
            e.printStackTrace();
        }

        // 对所有请求信息进行判断
        Iterator iter = (Iterator) items.iterator();
        String s[] = new String[3];//我们传过来的可能是多个数据,包含文件类型的和非文件类型的,创建一个数组循环获取传过来的数据
        int i = 0;
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            // 信息为普通的格式
            if (item.isFormField()) {
            	String field = item.getFieldName();// 表单域名
            	s[i++] = item.getString("UTF-8");//对于普通的文本,我们直接将其内容存入数组
            }
            // 信息为文件格式
            else {
            	if(item.getName()!=null&&item.getName()!=""){//判断文件是否为空
         		   	fileName = item.getName();//获取文件名
         		   	//由于文件由很多不同用户上传,文件名可能会出现相同的情况,在这里我们对文件进行重命名
                    int index1 = fileName.lastIndexOf(".");//找到文件名中最后一个“.”,这一步是为了得到文件的扩展名
                    //我们采取根据系统时间生成时间戳来重命名文件  
                    // 获取指定格式的时间
                    
                    // 精确到毫秒,主要是为了防止用户量较大而产生相同时间戳
                    SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");
                    
                    //重命名当前时间+文件本身扩展名
                    fileName = df.format(new Date())+fileName.substring(index1,fileName.length());  
                     
					s[2] = fileName;   //将文件名存入数组
                    @SuppressWarnings("deprecation")
     				String basePath = request.getRealPath("/images");//文件保存到服务器的相对项目根目录的路径
                    File file = new File(basePath, fileName);
                    try {
                        item.write(file);	//将文件保存到指定位置
                    }
                    catch (Exception e) {
                        e.printStackTrace();
                    }
         	   }
            }
        }
 		//数据中间处理,存入bean
        Lai l = new Lai();
			
		l.setTitle(s[0]);
		l.setPlace(s[1]);
	    l.setFileName(s[2]);
        Connection con = null;
		try{
			con = db.getCon();
			ll.insert(con,l);//调用存库
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try {
				this.db.closeCon(con);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
}
//存数据库
public int insert(Connection con,Lai l)throws Exception{
		String sql = "insert yb_come(mdatetime,placeimg,filename) values(?,?,?)";
		
		try {

		//获取一个用来执行SQL语句的对象   QueryRunner
		QueryRunner qr = new QueryRunner();
		
		Object[] params = {l.getTitle(),l.getPlace(), l.getFileName()};//存放数据
		
		return = qr.update(con,sql,params);//执行存贮
		
		} catch (SQLException e) {
		throw new RuntimeException(e);
		}	
	}

后续在前端再次调用该文件是(例如是一张图片)

<img src="<%=basePath%>/images/${l.filename}" data-preview-src="" data-preview-group="1" style="width:200px;height:200px"/>
<--调用图片路径的时候,写上文件存放的固定路径,然后在加上从数据库中查询出来的文件名即可(存储时文件名中已包含文件扩展名)-->
  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值