- 浏览: 108591 次
- 性别:
- 来自: 北京
最新评论
-
ocean1999:
有代码没 想学习哈 邮箱65614435@qq.com ,非常 ...
使用Google app做了个文件上传网站 http://avatar-share.appspot.com -
mywayscut:
很不错。详细介绍下吧,上传到blob的实现的怎么样的
使用Google app做了个文件上传网站 http://avatar-share.appspot.com
以前写的Google App Engine上传程序,贴出来上传这部分代码给大家分享下。
不知道现在Google还有没有限制,我以前测试的能上传10M左右。否则就会超时错误。
1. 上传的代码
public void uploadAction(HttpServletRequest req, Page p) throws IOException, ServletException { String path = getHomeUrl(req); boolean isMultipart = ServletFileUpload.isMultipartContent(req); long id = -1; if (isMultipart) { ServletFileUpload uploader = new ServletFileUpload(); uploader.setFileSizeMax(MAX_FILE_SIZE); try { FileItemIterator it = uploader.getItemIterator(req); DataFile df = new DataFile(); df.setDownloadTimes(0); while (it.hasNext()) { FileItemStream item = it.next(); if(item.isFormField()){ String value = readString(item.openStream()); if(item.getFieldName().equals("categoryId")) df.setCategoryId(Integer.valueOf(value)); else if(item.getFieldName().equals("title")) df.setTitle(value); else if(item.getFieldName().equals("description")) df.setDescription(new Text(value)); }else{ String filename = getFileName(item.getName()); if(isBlank(filename)) break; df.setFilename(filename); df.setContentType(ContentType.fetchMatchContentType(filename)); df.setPostDate(new Date(System.currentTimeMillis())); service.add(df); id = df.getId(); saveFile(item.openStream(), df); service.update(df); } } if(df.getId() != null){ String url = path+ "/" + df.getId() + "/show.html"; FileCategory cat = catService.get(df.getCategoryId()); p.put("category", cat == null?"":cat.getName()); p.put("durl", getHomeUrl(req)+"/file/"+df.getId()+"_"+df.getFilename()); p.put("url", url); p.put("file", df); p.put("message", "文件上传成功!"); p.setTemplate("filedata_show.ftl"); }else{ p.put("message", "文件上传失败!"); uploadformAction(req, p); } } catch (Exception e) { e.printStackTrace(); p.put("message", "文件上传失败!文件大小不能超过10M!"); if(id>-1){ service.delete(id); blockService.deleteBlocksOfFile(id); } uploadformAction(req, p); } } } private void saveFile(InputStream in, DataFile df) throws IOException{ int len, size = 0, totalSize = 0; int sn = 1; if(in.available() > MAX_FILE_SIZE){ System.out.println("file to big!"); throw new IOException("Too Large"); } while ((len = in.read(buffer)) != -1) { if((size + len) > Block_SIZE){//save this block DataBlock block = new DataBlock(); block.setSize(size); block.setFileId(df.getId()); block.setSn(sn++); byte[] byt = Arrays.copyOf(data, size); Blob bo = new Blob(byt); block.setData(bo); blockService.add(block); size = 0; } System.arraycopy(buffer, 0, data, size, len); size += len; totalSize += len; } if(size > 0){ DataBlock block = new DataBlock(); block.setSize(size); block.setFileId(df.getId()); block.setSn(sn++); byte[] byt = Arrays.copyOf(data, size); Blob bo = new Blob(byt); block.setData(bo); blockService.add(block); } df.setSize(totalSize); in.close(); }
2. 下载的代码
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpSession session = req.getSession(); String seStr = (String)session.getAttribute(Constants.VERIFY_CODE); String inputStr = req.getParameter("verify_code"); if(inputStr != null && inputStr.equals(seStr)){ String url = req.getRequestURI(); int ind = url.lastIndexOf("/"); if(ind == -1) return; String temp[] = url.split("/"); String filename = temp[temp.length - 1]; ind = filename.indexOf("_"); String id = filename.substring(0, ind); filename = filename.substring(ind + 1); if(id != null){ DataFile df = fservice.get(Long.valueOf(id), false); if(df != null){ resp.setContentType(df.getContentType()); ServletOutputStream os = resp.getOutputStream(); List<DataBlock> dbs = service.blocksOfFile(Long.valueOf(id)); for(DataBlock db : dbs) os.write(db.getData().getBytes()); fservice.updateDownloadTimes(Long.valueOf(id)); }else{ Page page = new Page(); page.put("home", getHomeUrl(req)); page.put("message", "要下载的文件不存在!"); page.setTemplate("filedata_error.ftl"); Template t = cfg.getTemplate(page.getTemplate()); Writer out = new BufferedWriter( new OutputStreamWriter( resp.getOutputStream(), t.getEncoding())); resp.setContentType("text/html; charset=" + t.getEncoding()); resp.setHeader("Cache-Control", "no-cache"); resp.setHeader("Pragma", "no-cache"); resp.setHeader("Expires", "Thu, 01 Dec 2010 00:00:00 GMT"); try { t.process(page.getRoot(), out); out.flush(); } catch (TemplateException e) { e.printStackTrace(); resp.sendRedirect("error.htm"); } } } }else{ doGet(req, resp); } }
3. 和freemarker集成的Controller
import java.io.*; import java.lang.reflect.Method; import javax.servlet.*; import javax.servlet.http.*; import com.hchen.pubshare.service.FileCategoryService; import com.hchen.pubshare.service.impl.FileCategoryServiceImpl; import com.hchen.pubshare.util.Page; import freemarker.template.*; public abstract class ControllerServlet extends HttpServlet { private static final long serialVersionUID = -754687385885208233L; private Configuration cfg; private FileCategoryService catService = new FileCategoryServiceImpl(); public void init() { cfg = new Configuration(); cfg.setServletContextForTemplateLoading( getServletContext(), "WEB-INF/templates"); // - Set update dealy to 0 for now, to ease debugging and testing cfg.setTemplateUpdateDelay(0); // - Set error handler for debugging HTML templates // cfg.setTemplateExceptionHandler( // TemplateExceptionHandler.HTML_DEBUG_HANDLER); // - Use beans wrapper cfg.setObjectWrapper(ObjectWrapper.BEANS_WRAPPER); // - Set default charset cfg.setDefaultEncoding("UTF-8"); cfg.setDateTimeFormat("yyyy-MM-dd HH:mm:ss"); cfg.setNumberFormat("############"); } protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try{ String action = req.getServletPath(); if (action == null) action = "index"; if (action.lastIndexOf("/") != -1) action = action.substring(action.lastIndexOf("/") + 1); if (action.lastIndexOf(".") != -1) action = action.substring(0, action.lastIndexOf(".")); Method actionMethod = getClass().getMethod(action + "Action", new Class[]{HttpServletRequest.class, Page.class}); Page page = new Page(); page.put("message", ""); page.put("home", getHomeUrl(req)); processRequestParameters(req.getServletPath(), action, page); actionMethod.invoke(this, new Object[]{req, page}); if (page.getTemplate() != null) { // show a page with a template Template t = cfg.getTemplate(page.getTemplate()); Writer out = new BufferedWriter( new OutputStreamWriter( resp.getOutputStream(), t.getEncoding())); resp.setContentType("text/html; charset=" + t.getEncoding()); resp.setHeader("Cache-Control", "no-cache"); resp.setHeader("Pragma", "no-cache"); resp.setHeader("Expires", "Thu, 01 Dec 2010 00:00:00 GMT"); t.process(page.getRoot(), out); out.flush(); } else if (page.getForward() != null) { // forward request if(page.isDispatch()){ RequestDispatcher rd = req.getRequestDispatcher(page.getForward()); rd.forward(req, resp); }else{ resp.sendRedirect(page.getForward()); } } else { // Ops! throw new ServletException("The action didn't specified command."); } }catch(Exception ex){ ex.printStackTrace(); resp.sendRedirect("error.htm"); } } public static String noNull(String s) { return s == null ? "" : s; } public static boolean isBlank(String s) { return s == null || s.trim().length() == 0; } public String getHomeUrl(HttpServletRequest req){ String path = null; if (req.getServerPort() == 80 ) path="http://"+req.getServerName(); else path="http://"+req.getServerName()+":"+req.getServerPort(); return path; } public void processRequestParameters(String path, String action, Page page){ if(isBlank(action)) return; String temps[] = path.split("/"); int len = temps.length; if(action.equals("show")){ if(temps.length > 2) page.addReqParameter("id", temps[len - 2]); }else if(action.equals("list")){ if(temps.length > 3){ page.addReqParameter("dir", temps[len - 3]); page.addReqParameter("offset", temps[len - 2]); } } } }
完整代码上传到 google code了,以前做的一个文件上传的Google App,现在不弄这个了。
svn checkout http://pubshare.googlecode.com/svn/trunk/ pubshare-read-only
发表评论
-
访问需要HTTP Basic Authentication认证的资源的各种语言的实现
2011-12-02 12:23 1695无聊想调用下嘀咕的api的时候,发现需要HTTP Bas ... -
设计一个不用OAuth的安全的REST接口
2011-12-02 12:09 1987You want to develop a RESTfu ... -
wordpress 内网外网访问问题
2011-04-08 01:29 4944在实验室的服务器上部署了wordpress,发现在外网访问正常 ... -
使用Google app做了个文件上传网站 http://avatar-share.appspot.com
2010-02-24 12:20 1439使用google app engine开发了一个文件分享网站, ... -
nginx + mongrel 配置文件
2009-12-04 16:25 9791 nginx 配置文件 user hchen; work ... -
GAE paging
2009-11-19 14:51 750Hi all! There's been a lot of g ... -
GAE with spring实践经验
2009-11-16 09:59 892最近看到很多人研究GAE,这周末我也花了两天时间用GAE + ... -
struts2多文件上传
2009-05-14 10:53 996import java.io.File; import ja ... -
使用XDoclet反向生成hibernate映射文件和DDL
2009-05-04 17:16 18201 在编写vo文件时候在类和字段的注释上添加xdoclet使用 ... -
hibernate many-to-many实例
2009-04-24 16:08 2654该实例有两个对象User和Group,User和Group建立 ... -
使用自定义拦截器加载字典表
2009-04-22 17:20 1428使用自定义拦截器可以直接实现接口com.opensymphon ... -
Javascript动态添加,删除表格行的例子
2009-04-18 00:00 1372最近又开始做Web项目,完全又成新手了,几年前就没仔细看过Ja ... -
Struts2 validate
2009-04-17 16:13 1922如何让Validate验证只验证指定的方法? 比如update ...
相关推荐
4.6 文件上传——FileUpload 4.7 时间选择器——DatePicker 4.8 列表控件——ListBox 4.9 联想输入框——Suggest Box 4.10 树结构——Tree 4.11 菜单条——MenuBar 4.12 栈板——StackPanel 4.13 基本输入框的——...
您可以简单地使用JavaScript代码发送电子邮件,在Google电子表格中添加CRUD数据,将文件上传到Google驱动器,在Google calander上设置/删除提醒等等。 简而言之,您可以使用我为MIT Appinventor及其扩展及其Niotron...
Java二进制IO类与文件复制操作实例,好像是一本书的例子,源代码有的是独立运行的,与同目录下的其它代码文件互不联系,这些代码面向初级、中级Java程序员。 Java访问权限控制源代码 1个目标文件 摘要:Java源码,...
SDBlog是一款使用Python编写的运行在Google Appengine上的单用户免费博客程序。现在它的1.0Beta版本已将发布 现在将SDBlog1.0Beta版的功能做下介绍。 浏览显示 文章列表显示和摘要显示两种显示方式; ...
PowerPoint(.pptx)演示文稿上传和转换为Google Course Builder数据格式,简化了Google Course Builder MOOC的创建。 源代码最初是拉夫堡大学的硕士学位项目,现在已变为开放源代码,以使社区能够进一步开发该产品...
Java二进制IO类与文件复制操作实例,好像是一本书的例子,源代码有的是独立运行的,与同目录下的其它代码文件互不联系,这些代码面向初级、中级Java程序员。 Java访问权限控制源代码 1个目标文件 摘要:Java源码,...
为了支持img文件夹之外的文件上传(即,允许您上传新的基本图像而不必每次都重新部署该应用程序) 在您的GAE应用上启用结算功能。 启用Google云端存储。 要授予其他用户上载图像的权限,您需要将其作为管理员添加...
$ go get -u google.golang.org/appengine/cmd/aedeploy 确保您已登录 : $ gcloud auth login 部署flexdev服务器: $ flexdev server deploy -project your-project -version flexdev 快速部署您的应用程序代码...
可与支持标准HTML表单文件上传的任何服务器端平台(Google App Engine,PHP,Python,Ruby on Rails,Java等)一起使用。 -Faker是一个PHP库,可以为您生成假数据-PHP依赖管理器 -Symfony PHP框架guzzle guzzle-...
Wahlzeit是Google App Engine应用程序,可以在您的本地计算机上使用,也可以部署到Google App Engine以在线访问它。 有关更多信息,请参见和 。第二部分:WAHLZEIT设置首先下载资料库: 满足先决条件:安装Java JDK...
它是使用 Google App Engine 部署的 待办事项: 允许上传 Json 文件 允许切换卫星视图(适合查看电力线和发电机) 从 Open Streetmaps 中拉出传输线图层并覆盖它 允许并行上传/可视化多个价格组件,可能通过多...
本指南的创建旨在帮助用户使用本地存储的文件,使用Google Cloud Platform(GCP)App Engine部署破折号应用程序。 有关更多信息,请访问。 注意:此博客自首次发布以来已被更新。 有关更改,请参见帖子底部的“版本...
simian simian-import是一个go二进制文件,用于将pkgsinfo文件上传到Simian。 即使不推荐使用Simian的uploadpkg视图/端点,这也可以启用autopkg集成。 要测试上传到Simian实例的文件,请安装gcloud命令行工具,并以...
Google App Engine v. 53. 接下来阅读什么 8. VII. Spring Boot CLI i. 54. 安装CLI ii. 55. 使用CLI i. 55.1. 使用CLI运行应用 i. 55.1.1. 推断"grab"依赖 ii. 55.1.2. 推断"grab"坐标 iii. 55.1.3. 默认import...
Protobuf & json | 数据序列化 | [https://github.com/google/protobuf](https://github.com/google/protobuf) Jenkins | 持续集成工具 | [https://jenkins.io/index.html](https://jenkins.io/index.html) Maven | ...