首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

异步的多文件下传和文件存储代码

2012-10-10 
异步的多文件上传和文件存储代码这一段代码是在工作之余自己练手玩的代码,因为不喜欢引入别人的js,就自己

异步的多文件上传和文件存储代码

这一段代码是在工作之余自己练手玩的代码,因为不喜欢引入别人的js,就自己写一个jsp的页面,以后可以重用,界面上是达不到商业软件的标准了,但是功能还是实现了的。


这个异步的多文件上传初衷是为了上传图片,所以有个预览图这一栏。


/** * 图片上传 * @param request * @param response * @throws ServletException * @throws IOException */private void imgUpload(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {String fileType = request.getParameter("fType");BufferedInputStream fin = new BufferedInputStream(request.getInputStream());//生成随机文件名String fileName = uuid.generate() + fileType;//path是本地路径String path = getURI() + "/uploadFolder/" + fileName;//uploadBasePath是从前台页面拿到的网页路径String uploadBasePath = request.getParameter("uploadBasePath");String imgAlt = request.getParameter("imgAlt");if(null != uploadBasePath && imgAlt != null){//url拼接出来以后是http://xxx.xxx.xxx/smdtx/uploadFolder/xxxx.jpgString url = uploadBasePath + "uploadFolder/" + fileName;PrintWriter out = response.getWriter();if(saveFile(fin,path)){//成功了就返回url给jsp页面Image img = new Image();img.setUrl(url);img.setAlt(imgAlt);try{imgDao.add(img);out.write(url);out.flush();}catch(Exception e){mLog.error(" method imgUpload() catch exception by " + e.getMessage());e.printStackTrace();}finally{if(out != null){out.close();}}}else{try{out.write("false");out.flush();}catch(Exception e){mLog.error(" method imgUpload() catch exception by " + e.getMessage());e.printStackTrace();}finally{if(out != null){out.close();}}}}}/** * 保存文件到本地 * @param in 输入流 * @param path 保存地址 * @return boolean 成功标识  * @throws IOException */private boolean saveFile(InputStream in,String path) throws IOException{File file = new File(path);byte[] buff = new byte[1024];int buffLength = -1;OutputStream out = null;boolean result = false;try{out = new FileOutputStream(file);while((buffLength = in.read(buff)) != -1){out.write(buff, 0, buffLength);}result = true;}catch(Exception e){mLog.error(" method saveFile() catch exception by " + e.getMessage());e.printStackTrace();}finally{if(out != null){out.close();}}return result;}

大概就是这个样子。自己有一个疑问,为什么最后一个file路径返回了多次?希望有经验的朋友能够留言解惑。

热点排行