使用Cos时,可以使用两个类来进行上传工作:
1. MultipartRequest
2. MultipartParser
一般情况下会使用MultipartRequest类,我感觉它比MultipartParser更方便一些(事实上MultipartRequest封装了MultipartParser),在构造MultipartRequest实例时,构造了MultipartParser实例(构造parser的过程取得了上传的数据流引用,但并未真正读取)。
然后通过MultipartParser的readNextPart()方法,从request流中读取数据,区别出流中的参数域和文件域,如果是参数的话用ParamPart类封装;如果是文件的话用FilePart封装。
此时如果设置了重命名策略的话,则在服务器端新建一个新命名的空文件,然后调用FilePart的writeTo(saveDir)方法将流数据写到磁盘中。至此,文件上传完成。
下面是使用MultipartRequest的上传类示例:
/**//*
* DemoUploadServlet.java
*
* Example servlet to handle file uploads using MultipartRequest for
* decoding the incoming multipart/form-data stream
*/
import java.util.Enumeration;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
public class DemoRequestUploadServlet extends HttpServlet {
private String dirName;
public void init(ServletConfig config) throws ServletException {
super.init(config);
// read the uploadDir from the servlet parameters
dirName = config.getInitParameter("uploadDir");
if (dirName == null) {
throw new ServletException("Please supply uploadDir parameter");
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/plain");
out.println("Demo Upload Servlet using MultipartRequest");
out.println();
try {
// Use an advanced form of the constructor that specifies a character
// encoding of the request (not of the file contents) and a file
// rename policy.
MultipartRequest multi =
new MultipartRequest(request, dirName, 10*1024*1024,
"ISO-8859-1", new DefaultFileRenamePolicy());
out.println("PARAMS:");
Enumeration params = multi.getParameterNames();
while (params.hasMoreElements()) {
String name = (String)params.nextElement();
String value = multi.getParameter(name);
out.println(name + "=" + value);
}
out.println();
out.println("FILES:");
Enumeration files = multi.getFileNames();
while (files.hasMoreElements()) {
String name = (String)files.nextElement();
String filename = multi.getFilesystemName(name);
String originalFilename = multi.getOriginalFileName(name);
String type = multi.getContentType(name);
File f = multi.getFile(name);
out.println("name: " + name);
out.println("filename: " + filename);
out.println("originalFilename: " + originalFilename);
out.println("type: " + type);
if (f != null) {
out.println("f.toString(): " + f.toString());
out.println("f.getName(): " + f.getName());
out.println("f.exists(): " + f.exists());
out.println("f.length(): " + f.length());
}
out.println();
}
}
catch (IOException lEx) {
this.getServletContext().log(lEx, "error reading or saving file");
}
}
}
下面是使用MultipartParser的代码示例:
/**//*
* DemoParserUploadServlet.java
*
* Example servlet to handle file uploads using MultipartParser for
* decoding the incoming multipart/form-data stream
*/
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import com.oreilly.servlet.multipart.*;
public class DemoParserUploadServlet extends HttpServlet {
private File dir;
public void init(ServletConfig config) throws ServletException {
super.init(config);
// Read the uploadDir from the servlet parameters
String dirName = config.getInitParameter("uploadDir");
if (dirName == null) {
throw new ServletException("Please supply uploadDir parameter");
}
dir = new File(dirName);
if (! dir.isDirectory()) {
throw new ServletException("Supplied uploadDir " + dirName +
" is invalid");
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/plain");
out.println("Demo Upload Servlet using MultipartParser");
out.println();
try {
MultipartParser mp = new MultipartParser(request, 10*1024*1024); // 10MB
Part part;
while ((part = mp.readNextPart()) != null) {
String name = part.getName();
if (part.isParam()) {
// it's a parameter part
ParamPart paramPart = (ParamPart) part;
String value = paramPart.getStringValue();
out.println("param: name=" + name + "; value=" + value);
}
else if (part.isFile()) {
// it's a file part
FilePart filePart = (FilePart) part;
String fileName = filePart.getFileName();
if (fileName != null) {
// the part actually contained a file
long size = filePart.writeTo(dir);
out.println("file: name=" + name + "; fileName=" + fileName +
", filePath=" + filePart.getFilePath() +
", contentType=" + filePart.getContentType() +
", size=" + size);
}
else {
// the field did not contain a file
out.println("file: name=" + name + "; EMPTY");
}
out.flush();
}
}
}
catch (IOException lEx) {
this.getServletContext().log(lEx, "error reading or saving file");
}
}
}