org.apache.commons.fileupload 路径

mayflowers posted @ 2008年6月22日 21:27 in Java , 2661 阅读

用org.apache.commons.fileupload 上传文件:

DiskFileUpload.setRepositoryPath(path)

FileItem.write( new File(fullpath)

上面两个方法的path 都是物理路径, (好像 jspsmartupload 是虚拟路径,但是这个已经不好找了,而且据说对中文文件有问题),如果要用虚拟路径的话,就需要用ServletContext中的getRealPath函数:

DiskFileUpload.setRepositoryPath(application.getRealPath(virtualpath))

FileItem.write( new File(application.getRealPath(virtualpath)+"/"+filename)

 下面是个例子, 把上传的文件按原来的名字保存在 /upsave 下:

  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
  2. <%@ page import="org.apache.commons.fileupload.*" %>
  3. <%@ page import="java.io.*" %>
  4. <%@page import="org.apache.commons.io.*" %>
  5.  
  6. <%
  7.   DiskFileUpload diskfile = new DiskFileUpload();
  8.                
  9.   diskfile.setSizeMax( 100*1024*1024 )// 允许文件最大长度
  10.  
  11.   diskfile.setSizeThreshold(4096);      // 设置内存缓冲大小
  12.  
  13.   diskfile.setRepositoryPath(application.getRealPath("/tmp"));
  14.                     // 设置临时目录
  15.   List fileItems = diskfile.parseRequest(request);
  16.   Iterator iter = fileItems.iterator();
  17.  
  18.    for( ; iter.hasNext(); ) {
  19.  
  20.          FileItem fileItem = (FileItem) iter.next();
  21.         if( fileItem.isFormField() ) {
  22.                             // 当前是一个表单项
  23.          out.println( fileItem.getFieldName() + "=" + fileItem.getString() );
  24.    }
  25.  else {
  26.                             // 当前是一个上传的文件
  27.          String fileName = fileItem.getName();
  28.          String fname=fileName.substring(fileName.lastIndexOf("\\")+1); //取得文件名
  29.          if(fname!=null && !fname.trim().equals("")){
  30. //是否有文件上传
  31.             fileItem.write( new File(application.getRealPath("/upsave")+"\\"+fname));
  32.            }
  33.    }
  34. }
  35. %>
WBBSE 10th Question 说:
2022年8月18日 12:44

The exams will be held in the months of February & March 2023. The students who will be appearing for the secondary exams can download the WB Madhyamik 10th Exam Guess Paper 2023, WB Madhyamik 10th Exam New Model Paper 2023, WBBSE 10th Question Paper 2023 WB Madhyamik 10th Sample Question Paper 2023, West Bengal WB WBBSE 10th Model Question Paper 2023 from the official website or from our website in the month of November 2023.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter