< %@ page import="java.io.*"%> < %@ page import="java.util.*"%> < %@ page import="java.text.SimpleDateFormat"%> < meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> < % int MAX_SIZE = 1024 * 1024 * 1; String rootPath = request.getRealPath("/") + "/upload/"; String contentType=request.getContentType(); try{ if(contentType.indexOf("multipart/form-data") >= 0){ DataInputStream in = new DataInputStream(request.getInputStream()); int formDataLength = request.getContentLength(); if(formDataLength > MAX_SIZE){ out.println("<script>alert('上传的文件字节数不可以超过" + MAX_SIZE + "');window.history.go(-1);</script>"); return; } byte dataBytes[] = new byte[formDataLength]; int byteRead = 0; int totalBytesRead = 0; while(totalBytesRead < formDataLength){ byteRead = in.read(dataBytes,totalBytesRead,formDataLength); totalBytesRead += byteRead; } String file = new String(dataBytes); String oldFileName = file.substring(file.indexOf("filename=\"") + 10); oldFileName = oldFileName.substring(0,oldFileName.indexOf("\n")); oldFileName = oldFileName.substring(oldFileName.lastIndexOf("/") + 1,oldFileName.indexOf("\"")); String sExt = oldFileName.substring(oldFileName.lastIndexOf("."),oldFileName.length()); java.util.Date dt = new java.util.Date(System.currentTimeMillis()); SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS"); String nenFileName= fmt.format(dt) + sExt; String fileName = rootPath + nenFileName; int lastIndex = contentType.lastIndexOf("="); String boundary = contentType.substring(lastIndex + 1,contentType.length()); int pos; pos = file.indexOf("filename=\""); pos = file.indexOf("\n",pos) + 1; pos = file.indexOf("\n",pos) + 1; pos = file.indexOf("\n",pos) + 1; int boundaryLocation = file.indexOf(boundary,pos) - 4; int startPos = ((file.substring(0,pos)).getBytes()).length; int endPos = ((file.substring(0,boundaryLocation)).getBytes()).length; File fileDir = new File(rootPath); if(!fileDir.exists()){ fileDir.mkdirs(); } FileOutputStream fileOut = new FileOutputStream(fileName); fileOut.write(dataBytes,startPos,(endPos - startPos)); fileOut.close(); out.println("<script>alert('上传成功!')</script>"); }else{ String content = request.getContentType(); out.println("<p>上传的数据类型不是multipart/form-data</p>"); } }catch(Exception ex){ throw new ServletException(ex.getMessage()); } %>
public class Test { public static String numerFormat(double d) { NumberFormat nf=NumberFormat.getNumberInstance(); nf.setMaximumFractionDigits(2); return nf.format(d); } } |
|