关闭

jatarta fileupload 实例

2051人阅读 评论(0) 收藏 举报
<%
  //1.首先在http://jakarta.apache.org/commons/index.html下载FileUpload和IO的jar包,并放到WEB-INF/lib中;
  //2.如下代码:
%>
<%@page contentType="text/html; charset=GBK"%>
<%@page import="java.io.*,java.util.*,org.apache.commons.fileupload.*,org.apache.commons.fileupload.disk.*,org.apache.commons.fileupload.servlet.* "%>
<html>
<head>
<title>upload</title>
</head>
<body bgcolor="#ffffff" style="font-family:Arial">
<h1>jakarta fileupload test</h1>
<form method="post" action="upload.jsp" enctype="multipart/form-data">
<br>
<br>
file:
<input type="file" name="file"/>
<br>
Txt:
<input type="text" name="Txt">
<input type="submit" name="Submit" value="Submit">
<input type="reset" value="Reset">
</form>
</body>
</html>
<%
  boolean isMultipart = ServletFileUpload.isMultipartContent(request);
  Map req = new HashMap();
  Map uploadFile = new HashMap();
  if (isMultipart) {
    // Create a factory for disk-based file items
    FileItemFactory factory = new DiskFileItemFactory();
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // Parse the request
    List items = null; /* FileItem */
    try {
      items = upload.parseRequest(request);
    }
    catch (FileUploadException e) {
      out.println(e);
    }
    // Process the uploaded items
    Iterator iter = items.iterator();
    while (iter.hasNext()) {
      FileItem item = (FileItem) iter.next();
      if (item.isFormField()) {
        String name = item.getFieldName();
        String value = new String(item.getString().getBytes("ISO8859-1"), "GBK");
        req.put(name, value);
      }
      else {
        String fieldName = item.getFieldName();
        uploadFile.put(fieldName, item);
      }
    }
    items.clear();
  }
  if (!isMultipart) {
    return;
  }
  //TEST
  //request.getParameter("Txt");
  String key = "Txt";
  String value = req.get(key).toString();
  out.println(key + "=" + value);
  //save upload File "file"
  FileItem item = (FileItem) uploadFile.get("file1");
  out.print(item);
  if (item != null) {
    String filePath = item.getName(); //全路径文件名
    String fileName = filePath.replaceAll("////", "/");
    fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
    String contentType = item.getContentType();
    boolean isInMemory = item.isInMemory();
    long sizeInBytes = item.getSize();
    File uploadedFile = new File("e:/" + fileName);
    try {
      item.write(uploadedFile);
    }
    catch (Exception e) {}
  }
%>
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:424798次
    • 积分:5662
    • 等级:
    • 排名:第4822名
    • 原创:134篇
    • 转载:15篇
    • 译文:2篇
    • 评论:127条
    文章分类