直接上浏览器端upload.jsp代码(为测试服务器端)
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>upload</title> </head> <body> <center> <!-- /Myweb/upload.do --> <form action="${pageContext.request.contextPath}/upload.do" method="post" enctype="multipart/form-data"> <table> <tr> <td> Name </td> <td> <input type="text" name="Name"> </td> </tr> <tr> <td> Gender </td> <td> <input type="text" name="Gender"> </td> </tr> <tr> <td> 请选择一个上传文件 </td> <td> <input type="file" name="Image"> </td> </tr> <tr> <td> <input type="submit" value="上传"> </td> <td> <input type="reset" value="重置"> </td> </tr> </table> </form> </center> </body> </html>
<form action="${pageContext.request.contextPath}/upload.do" method="post" enctype="multipart/form-data"> 注意enctype="multipart/form-data" (复杂的数据提交)和{pageContext.request.contextPath}/upload.do工程访问路径
还有就是字符集统一使用utf-8 小心中文乱码。
2.服务器端,采用commons-fileupload 来实现文件上传,仍然使用Servlet
commons-fileupload-1.3.1.jar+ commons-io-2.4.jar(本人出现兼容报错)
代码如下
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); //判断是否是复杂表单提交 boolean isMutipart=ServletFileUpload.isMultipartContent(request); // if(isMutipart) { //配置缓存工厂 DiskFileItemFactory factory=new DiskFileItemFactory(); //设置缓存大小 factory.setSizeThreshold(1024*1024*2); File temp=new File("D:\\temp"); if (!temp.exists()) { temp.mkdir(); } factory.setRepository(temp); ServletFileUpload upload=new ServletFileUpload(factory); // upload.setHeaderEncoding("utf-8"); upload.setFileSizeMax(1024*1024*5); upload.setSizeMax(1024*1024*6); //获取提交的集合 try { List<FileItem>items=upload.parseRequest(request); if(items!=null) { for(FileItem item :items) { if(item.isFormField()) { //一般数据 System.out.println(item.getFieldName()); System.out.println(item.getString("utf-8")); } else { String pathString=item.getName(); if(pathString.contains("\\")) { int index=pathString.lastIndexOf("\\"); pathString=pathString.substring(index+1); } System.out.println(pathString); //复杂文件 try { item.write(new File("D:\\"+pathString)); response.getWriter().write("upload success!"); } catch (Exception e) { e.printStackTrace(); response.getWriter().write("upload fail."); } } } } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { return; } }
传送门:[rar文件] andriod、iOS服务器端代码之文件上传
时间: 2024-10-13 10:41:38