使用Servlet处理上传的文件
使用Servlet处理上传的文件?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
创新互联公司于2013年创立,先为石泉等服务建站,石泉等地企业,进行企业商务咨询服务。为石泉企业网站制作PC+手机+微官网三网同步一站式服务解决您的所有建站问题。
一.使用getReader()和getInputStream()
Demo1
//这是Servlet处理部分 import java.io.DataInputStream; import java.io.FileOutputStream; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; //Servlet implementation class uploadServlet @WebServlet("/upload") public class UploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; //@see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //读取请求Body byte[] body = readBody(request); //取得所有Body内容的字符串表示 String textBody = new String(body, "ISO-8859-1"); //取得上传的文件的文件名(取得路径并分离) String filename = getFilename(textBody); //取得文件内容在Body中的首尾索引 Position p = getFilePosition(request, textBody); //将内容输出到文件 writeTo(filename, body, p); } //存放索引的类 class Position{ int begin; int end; Position(int begin, int end) { this.begin = begin; this.end = end; } } //读取请求body private byte[] readBody(HttpServletRequest request) throws IOException { int formDataLength = request.getContentLength(); //获得ServletInputStream对象 //getReader()和getInputStream()只能则一调用,否则会抛出IllegalStateException异常 DataInputStream dataStream = new DataInputStream(request.getInputStream()); byte[] body = new byte[formDataLength]; int totalBytes = 0; while(totalBytes < formDataLength) { int bytes = dataStream.read(body, totalBytes, formDataLength); totalBytes += bytes; } return body; } //取得上传文件名称 private String getFilename(String reqBody) { //获取filename的value,10是filename="的长度 //通过后台调试我发现filename=后加的是带着双引号的路径名,在获取路径名时不需要分号所以在分离时就将分号也分离掉了 String filename = reqBody.substring(reqBody.indexOf("filename=\"") + 10); //找到文件名这行的末尾,过滤掉对于获取文件名而言的无用信息 filename = filename.substring(0, filename.indexOf("\n")); //获取不包含路径名的文件名 filename = filename.substring(filename.lastIndexOf("\\") + 1, filename.lastIndexOf("\"")); //此时后台打印分离路径后的文件名并将其作为返回值返回 System.out.println(filename); return filename; } //取得文件开始和结束位置 private Position getFilePosition(HttpServletRequest request, String textBody) throws IOException { //取得文件区段边界信息 String contentType = request.getContentType(); String boundaryText = contentType.substring( contentType.lastIndexOf("=") + 1, contentType.length()); //取得实际上传文件的起始与结束位置 int pos = textBody.indexOf("filename=\""); pos = textBody.indexOf("\n", pos) + 1; pos = textBody.indexOf("\n", pos) + 1; pos = textBody.indexOf("\n", pos) + 1; int boundaryLoc = textBody.indexOf(boundaryText, pos) - 4; int begin = ((textBody.substring(0, pos)).getBytes("ISO-8859-1")).length; int end = ((textBody.substring(0, boundaryLoc)).getBytes("ISO-8859-1")).length; return new Position(begin, end); } //输出至文件 private void writeTo(String filename, byte[] body, Position p) throws IOException { //默认上传的文件是在F:\\javaeeAroundFiles目录下 FileOutputStream fos = new FileOutputStream("F:\\javaeeAroundFiles\\later\\" + filename); fos.write(body, p.begin, (p.end - p.begin)); fos.flush(); fos.close(); } }
二.使用getPart()和getInputStream()
Demo2
//HTML代码块
//uploadPhotoDemo.java import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; //Servlet implementation class uploadPartDemo //Tomcat中必须设置@MutipartConfig标注才能使用getPart()相关API @MultipartConfig @WebServlet("/uploadPhoto") public class uploadPartDemo extends HttpServlet { private static final long serialVersionUID = 1L; //@see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub //getPart()获取Part对象 Part part = request.getPart("photo"); String filename = getFilename(part); writeTo(filename, part); } private String getFilename(Part part) { String header = part.getHeader("Content-Disposition"); //获取完整路径 String filename = header.substring(header.indexOf("filename=\"") + 10, header.lastIndexOf("\"")); //filename after substring is: F:\Entertainment\pictures\e5e893df874df44d99f06bc52504a65c.jpg System.out.println("filename after substring is: " + filename); //获取文件名 filename = filename.substring(filename.lastIndexOf("\\") + 1); //filename after 2 substring is: e5e893df874df44d99f06bc52504a65c.jpg System.out.println("filename after 2 substring is: " + filename); return filename; } private void writeTo(String filename, Part part) throws IOException, FileNotFoundException { InputStream is = part.getInputStream(); FileOutputStream fos = new FileOutputStream("F:\\javaeeAroundFiles\\later\\" + filename); byte[] buffer = new byte[1024]; int length = -1; while((length = is.read(buffer)) != -1) { fos.write(buffer, 0, length); } is.close(); fos.close(); } }
这个Demo和第一个代码最大的区别就是,通过getPart()方法获得了Part对象,通过part对象的getHeader()方法指定标头获得对应的值。
在Tomcat中要在Servlet上设置@MultipartConfig才能取得Part对象,否则getPart会得到null
@MultipartConfig含有的属性如下:
fileSizeThreshold:整数值设置,若上传文件大小超过设置门槛,则先写入缓存文件,默认值为0
location:字符串设置,设置写入文件时的目录,使用时与write方法一起使用,下一个Demo中演示如何使用,默认是空字符串
maxFileSize:限制上传文件大小,默认-1L即无限制
maxRequestSize:限制multipart/form-data请求个数,默认值为-1L
Demo3
使用Part的write方法进行文件的写入,HTML文件查看Demo2注释部分
//uploadPhotoDemo2.java import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; //Servlet implementation class uploadPartDemo2 //设置属性,这里的最后一级不用分隔符,可以与Demo2中writeTo方法的路径做一下对比 @MultipartConfig(location="F:\\javaeeAroundFiles\\later") @WebServlet("/uploadPhoto2") public class uploadPartDemo2 extends HttpServlet { private static final long serialVersionUID = 1L; //@see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //文件名中可能有中文字符所以进行编码设置,使用setCharacterEncoding()方法 request.setCharacterEncoding("UTF-8"); Part part = request.getPart("photo"); String filename = getFilename(part); //使用Part的write方法,写入location指定路径 part.write(filename); } //获取文件名与Demo2相同不放代码 private String getFilename(Part part) {} }
若要实现同时上传多个文件则可以使用getParts()方法,获取到的Part对象被保存在一个Collection中
Demo4
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; //Servlet implementation class uploadPartsDemo @MultipartConfig(location="F:\\javaeeAroundFiles\\later") @WebServlet("/uploadParts") public class uploadPartsDemo extends HttpServlet { private static final long serialVersionUID = 1L; //@see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); //使用foreach遍历获取每一个Part对象 for(Part part : request.getParts()) { if(part.getName().startsWith("file")) { String filename = getFilename(part); part.write(filename); } } } //与之前的getFilename()方法相同 private String getFilename(Part part) { }
看完上述内容,你们掌握使用Servlet处理上传的文件的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注创新互联行业资讯频道,感谢各位的阅读!
分享标题:使用Servlet处理上传的文件
分享网址:http://ybzwz.com/article/jsjegs.html