jatarta fileupload 实例

 
<%
  //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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值