一个jsp网站,jsp页面表单同时含有普通字段,和图片,上传的时候不能用一个servlet处理,后来想想,图片是以二进制流传到servlet然后接收处理的吧,而文字的普通字段应该不是这种方式,那么用servlet一个函数接收处理时的问题是不是出在这里??
但是,其他网站是怎么处理呢??先上传图片,然后返回路径在和其他字段一起传到数据库吗?
怎么同步?就是怎么一步一起上传成功?!
还有怎么给图片重命名!?
(Google不到...)
jsp页面form表单如下,我遇到问题,所以就分成两个表单form,如下所示:
后端的接收的servlet是:
private void found(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); /* //为解析类提供配置信息 DiskFileItemFactory factory = new DiskFileItemFactory(); //创建解析类的实例 ServletFileUpload sfu = new ServletFileUpload(factory); //开始解析 sfu.setFileSizeMax(1024*400); //每个表单域中数据会封装到一个对应的FileItem对象上 try { List items = sfu.parseRequest(request); //区分表单域 for (int i = 0; i < items.size(); i++) { FileItem item = items.get(i); //isFormField为true,表示这不是文件上传表单域 if(!item.isFormField()){ ServletContext sctx = getServletContext(); //获得存放文件的物理路径 //upload下的某个文件夹 得到当前在线的用户 找到对应的文件夹 String path = sctx.getRealPath("/found_picture"); System.out.println("***"+path); //获得文件名 //获得文件名 String fileName = item.getName(); System.out.println(fileName); picture="found_picture/"+fileName;//存到数据库的字段值 System.out.println("路径:"+picture); //该方法在某些平台(操作系统),会返回路径+文件名 fileName = fileName.substring(fileName.lastIndexOf("/")+1); File file = new File(path+"\\"+fileName); if(!file.exists()){ item.write(file); //将上传图片的名字记录到数据库中 } } } } catch (Exception e) { e.printStackTrace(); } */ String category = new String(request.getParameter("category").getBytes("ISO-8859-1"), "UTF-8");//获取参数,防止乱码! String place = new String(request.getParameter("place").getBytes("ISO-8859-1"), "UTF-8");// String details =new String(request.getParameter("details").getBytes("ISO-8859-1"), "UTF-8"); String picture=(String)request.getParameter("picture");;//存照片上传文件夹后的,相对路径地址,最后存进数据库 String time = (String)request.getParameter("time"); String uid = (String)request.getParameter("uid"); System.out.println("UploadAction。java-found()函数输出调试 uid路径:"+uid);//在控制台输出,看看参数有没有传到这里 System.out.println("UploadAction。java-found()函数输出调试 picture路径:"+picture);//在控制台输出,看看参数有没有传到这里 boolean ret = false; DbConn dbc = new DbConn(); ret = dbc.found_other_Upload(category,picture,time,place,details,uid); //存到数据库,成功后返回true?! response.setContentType("text/html; charset=UTF-8"); //传参数,防止中文乱码 if (ret == true) { response.sendRedirect("found.jsp?upload=ok"); } else { request.setAttribute("error", "found操作有误!请勿做渗透测试!"); request.getRequestDispatcher("error.jsp").forward(request, response); } }
你应该贴代码,会比较直观 = =
HTML表单里包含字符串参数和文件参数是不会有问题的,但是需要注意以下两个参数必须写:
发送方式是字符串和二进制流混合的,类似下面:
servlet该怎么处理怎么处理,参数不会干扰。
给图片重命名,按照文件哈希值,或者时间戳,或者用户信息什么的,或者组合起来都可以(不重复就行了)。