刚从ruby转做java,分个活做照片上传,开始感觉很崩溃,以为本人菜鸟一个,一见到流什么的就感觉很牛逼的东西我怎么会啊,自学加百度,做出来了,两种方法完成,关于js预览就不上传了,留作以后备用,也能帮助下和我一样的菜鸟
jsp页面
<form action="uploadPhoto.do" method="post" enctype="multipart/form-data"> 上传照片:<input type=file name="file" id="file" onchange="javascript:upload();"> <p><div id="localImag"><img id="preview" width=-1 height=-1 style="diplay:none" /></div></p> <img id="p_w_picpathp" style="display:none" src="<%=path%>/<%=realPath%>" width="300px;" height="350px;"/><br/> <input type="p_w_picpath" src="./p_w_picpaths/bto2.jpg"> //上传按钮 </form>
/** * 照片上传 * @author sixd * @throws IOException * @throws ServletException * */ @RequestMapping(value = "/uploadPhoto.do") public void uploadPhoto(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request,HttpServletResponse response) throws Exception { InputStream is = null; OutputStream os = null; List<Map<String,Object>> zplist = null; String responseText = ""; String changName = ""; String realPath = ""; String xh = (String) request.getSession().getAttribute("xh"); String path = request.getSession().getServletContext().getRealPath("drzp"); String fileName = file.getOriginalFilename(); try { zplist = zpscDao.findZpInfo(xh); int index = fileName.lastIndexOf("."); String endFlag = fileName.substring(index); changName = xh.concat(endFlag); File a = new File(path); if (!a.exists()) { //创建目录 a.mkdir(); } is = file.getInputStream(); os = new FileOutputStream(path+"\\"+changName); int len = 0; byte[] bytes = new byte[1024]; while((len = is.read(bytes))>0){ os.write(bytes, 0, len); } realPath = "drzp/"+changName+""; if(zplist != null && !zplist.isEmpty()){ zpscDao.updatePhotoPath(realPath); }else{ zpscDao.savePhotoPath(xhgh,realPath); } responseText="success"; } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); responseText="fail"; }finally{ is.close(); os.close(); } response.sendRedirect("sczp/zpsc.jsp?path="+realPath+"&responseText="+responseText+""); }
方法二、
/** * 上传照片 * @author sixd * @throws IOException * @throws ServletException * */ @RequestMapping(value = "/uploadPhoto.do") public void uploadPhoto(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request,HttpServletResponse response) throws Exception { Map<String, Object> map = null; List<Map<String,Object>> zplist = null; String responseText = ""; String xhgh = (String) request.getSession().getAttribute("xh") try { map = zpscDao.findStudentInfo(xh); zplist = zpscDao.findZpInfo(xh); if(map != null && map.size()>0){ String fileName = file.getOriginalFilename(); int index = fileName.lastIndexOf("."); String endFlag = fileName.substring(index); String changName = xhgh.concat(endFlag); System.out.println(path); File targetFile = new File(path, changName); if(!targetFile.exists()){ targetFile.mkdirs(); } file.transferTo(targetFile); String realPath = "xxxx"/"+changName+""; if(zplist != null && !zplist.isEmpty()){ zpscDao.updatePhotoPath(realPath); }else{ zpscDao.savePhotoPath(xh,realPath); } } } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); } response.sendRedirect("sczp/zpsc.jsp"); }
方法三、上传到数据里blob型
主要借鉴http://www.myexception.cn/database/628584.html
1.导入commons-fileupload-1.2.1.jar
2.配置上传<!-- 支持上传文件 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
3.jsp:
<form method="post" action="uploadp_w_picpath.do" name="form" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" name="sub" value="上传"> </form>
4.控制器:
@RequestMapping(value = "/uploadp_w_picpath.do") public void uploadPhoto(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request,HttpServletResponse response) throws Exception { try{ byte[] data = file.getBytes(); int id = uploadDao.FileUpload(data, file.getOriginalFilename()); } catch(Exception e){ e.printStackTrace(); } }
5.接口实现
public int FileUpload(byte[] data, String originalFilename) { String sql = "insert into img (img,name) VALUES (?,?)"; img blob Connection conn=null; try { conn = jdbcTemplate.getDataSource().getConnection(); PreparedStatement ps=conn.prepareStatement(sql); //注意 :大对象类型的 我们存入的是bytes[],这里要set object ps.setObject(1, data); ps.setString(2, originalFilename); ps.executeUpdate(); conn.commit(); ps.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); } return 0; }
上边这种写法比较笨,不想spring的
找到一个api但是因为没有时间,所以没有试着做一下,但是例子在下边,应该不难
http://docs.spring.io/spring/docs/1.1.4/api/org/springframework/jdbc/core/support/AbstractLobCreatingPreparedStatementCallback.html
public abstract class AbstractLobCreatingPreparedStatementCallback
extends Object
implements PreparedStatementCallback
Abstract PreparedStatementCallback implementation that manages a LobCreator. Typically used as inner class, with access to surrounding method arguments.
Delegates to the setValues
template method for setting values on the PreparedStatement, using a given LobCreator for BLOB/CLOB arguments.
A usage example with JdbcTemplate:
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); // reusable object LobHandler lobHandler = new DefaultLobHandler(); // reusable object jdbcTemplate.execute( "INSERT INTO p_w_picpathdb (p_w_picpath_name, content, description) VALUES (?, ?, ?)", new AbstractLobCreatingPreparedStatementCallback(lobHandler) { protected void setValues(PreparedStatement ps, LobCreator lobCreator) throws SQLException { ps.setString(1, name); lobCreator.setBlobAsBinaryStream(ps, 2, contentStream, contentLength); lobCreator.setClobAsString(ps, 3, description); } } );
Sin