Servlet中可以使用post请求上传文件,使用getReader()和getInputStream()自己处理,也可以使用getPart()或getParts()封装了一些功能的方法处理,getParts()可以同时上传多个文件。接下来使用四个Demo来练习一下使用方法
一.使用getReader()和getInputStream()
Demo1
<!-- 这是HTML代码块,窗体网页上显示的是一个选择文件的input框和一个upload的button --> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title></title> </head> <body> <form action="upload" method="post" enctype="multipart/form-data"> 选择文件:<input type="file" name="filename" value="" /><br> <input type="submit" value="Upload" name="upload" /> </form> </body> </html>
//这是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代码块 <!-- 该HTML供uploadPartDemo和uploadPartDemo2共同使用,使用时通过更改body的form的action属性值控制 --> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title></title> </head> <body> <form action="uploadPhoto" method="post" enctype="multipart/form-data"> 上传相片:<input type="file" name="photo" /><br><br> <input type="submit" value="上传" name="upload" /> </form> </body> </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含有的属性如下:
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
<!-- 该HTML是三个input选框,选择三个文件 --> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title></title> </head> <body> <form action="uploadParts" method="post" enctype="multipart/form-data"> 文件1:<input type="file" name="file1" value="" /><br> 文件2:<input type="file" name="file2" value="" /><br> 文件3:<input type="file" name="file3" value="" /><br><br> <input type="submit" value="上传" name="upload" /> </form> </body> </html>
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) { }
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对呐喊教程的支持。如果你想了解更多相关内容请查看下面相关链接
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。