1.表单上传;
先获取到part对象,然后在通过part对象读取输入流(inputStream),最后把文件写到特定的目录上即可;
表单上传的前端代码:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); resp.setCharacterEncoding("utf-8"); resp.getWriter() .append("<html>") .append("<head>") .append("</head>") .append("<body>") .append("<h1>") .append("文件上传示例") .append("</h1>") .append("<div style='padding: 20px;width: 300px;box-shadow: 0 0 10px #999;'>" + "<form action='/' method='post' enctype='multipart/form-data'>") .append("<p><input type='file' name='file' value=\"\"></p>") .append("<p><input type='submit' value='提交'></p>") .append("</form></div>") .append("</body>") .append("</html>"); }
表单上传的后台处理代码:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("application/json"); resp.setCharacterEncoding("utf-8"); Part part = req.getPart("file"); String file = "{"; file += "\"name\":\"" + part.getName()+"\",\n"; file += "\"contentType\":\"" + part.getContentType()+"\",\n"; file += "\"size\":\""+part.getSize()+"\",\n"; file += "\"url\":\"/upload/"+part.getSubmittedFileName()+"\",\n"; file += "\"submitFileName\":\""+part.getSubmittedFileName()+"\"}"; BufferedInputStream bufferedInputStream = new BufferedInputStream(part.getInputStream()); FileOutputStream outputStream = new FileOutputStream("d:/tmp/"+part.getSubmittedFileName()); int read; while ((read = bufferedInputStream.read()) != -1){ outputStream.write(read); } outputStream.close(); bufferedInputStream.close(); resp.getWriter() .append(file); }
2.js上传;
可以把图片通过FileReader对象读取转换成base64的文字,然后通过ajax上传到服务器,这个稍微简单很多.
服务器获取到上传的文本,通过分割及解密的方式,输出到存储目录中即可.
下面是base64处理的方法:
public void uploadBase64(String fieldName){ String savePath = "d:/tmp/"; String base64Data = this.request.getParameter(fieldName); this.fileName = "test.jpg"; this.url = savePath + this.fileName; BASE64Decoder decoder = new BASE64Decoder(); try { File outFile = new File(this.getPhysicalPath(this.url)); OutputStream ro = new FileOutputStream(outFile); byte[] b = decoder.decodeBuffer(base64Data); for (int i = 0; i < b.length; ++i) { if (b[i] < 0) { b[i] += 256; } } ro.write(b); ro.flush(); ro.close(); this.state=this.errorInfo.get("SUCCESS"); } catch (Exception e) { this.state = this.errorInfo.get("IO"); } }