以前写的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 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