关闭

fileupload

标签: stringinputfileexceptionstrutssecurity
827人阅读 评论(0) 收藏 举报
分类:

lib:commons-fileupload-1.1.jar;commons-io-1.2.jar

静态页面文件代码如下


<HTML>
<BODY>
<form name="form1" method="post" action="c4.jsp" enctype="multipart/form-data">

<table width="85%" border="0">
  <tr>
    <td>
        名字<input type="text" name="username" size="40">
    </td>
  </tr>

  <tr>
    <td>
     图片   <input type="file" name="imagefile" size="40">
    </td>
  </tr>

  <tr>
    <td>
      word  <input type="file" name="wordfile" size="40">
    </td>
  </tr>

  <tr>
    <td>复选框 
        <input type="checkbox" name="software" value="struts">
        Struts
        <input type="checkbox" name="software" value="tomcat">
        Tomcat
    </td>
  </tr>

  <tr>
    <td align="left">单选框:
      <input type="radio" name="team" value="indians">
      Indians
      <input type="radio" name="team" value="yankees">
      Yankees
    </td>
  </tr>

  <tr>
    <td>多选下拉:
      <select name="books" size="5" multiple>
        <option value="ajp">Advanced JavaServer Pages</option>
        <option value="sia">Struts In Action</option>
      </select>
    </td>
  </tr>

  <tr>
    <td colspan="2" align="center">
      <input type="submit" name="submit" value="提交">
    </td>
  </tr>
</table>
</form>
</BODY>
</HTML>

------------------------

c4.jsp的内容如下

<%@page import="practice.FileUpLoader2"%>
<%
 FileUpLoader2 fileUpload = new FileUpLoader2(request);
     fileUpload.upload(request);
request.getRequestDispatcher("msg.jsp").forward(request, response);
%>

------------------------

msg.jsp内容如下

<%@page language="java" contentType="text/html;charset=GBK"%>
<%if (request.getAttribute("message") != null){%>
<div><%=request.getAttribute("message")%><%request.removeAttribute("message")%}>  <div>

-----------------------

FileUpLoader2内容如下

package practice;


import java.io.File;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.DefaultFileItemFactory;
import org.apache.commons.fileupload.FileItem;


public class FileUpLoader2 {
    //文件上传出错后在页面提示的消息
    static StringBuffer message = new StringBuffer();
    //当上传文件超过限制时设定的临时文件位置
    private String tempPath = "d:\\tempzjd";

    //文件上传目标目录
    private String destinationPath = "d:\\tempzjd2";

    //获取的上传请求
    private HttpServletRequest fileuploadRequest = null;

    //设置最多只允许在内存中存储的数据,单位:字节
    private int sizeThreshold = 4096;

    //设置允许用户上传文件大小,单位:字节
    //共100M
    private long sizeMax = 104857600;

    public FileUpLoader2() {
    }


    public FileUpLoader2(HttpServletRequest fileuploadRequest) {
        this.fileuploadRequest = fileuploadRequest;
    }


    public void upload(HttpServletRequest request) throws FileUploadException {
        //如果请求不是文件上传,则返回
        if (!FileUpload.isMultipartContent(request)) {
            message.append("Request is not multipart!");
            request.setAttribute("message", message.toString());
            return;
        }
        //如果没有临时目录,则创建它
        if (!(new File(tempPath).isDirectory())) {
            try {
                new File(tempPath).mkdirs();
            } catch (SecurityException e) {
                System.out.println("can not make security direcoty");
            }
        }

        //如果没有上传目的目录,则创建它
        if (!(new File(destinationPath).isDirectory())) {
            try {
                new File(destinationPath).mkdirs();
            } catch (SecurityException e) {
                System.out.println("can not make security direcoty");
            }
        }

        DiskFileUpload fileUpload = new DiskFileUpload(new
                DefaultFileItemFactory());
//        DiskFileItemFactory factory = new DiskFileItemFactory();
        fileUpload.setSizeThreshold(sizeThreshold);
        fileUpload.setSizeMax(sizeMax);
        fileUpload.setRepositoryPath(tempPath);

        List items = fileUpload.parseRequest(request);
        Iterator itr = items.iterator();
        FileItem item;
        while (itr.hasNext()) {
            item = (FileItem) itr.next();

            String fieldName = item.getFieldName();
            if (item.isFormField()) { //对普通的form内容处理
                String fieldValue = item.getString();
                if (fieldName.equals("software")) {
                    System.out.println(fieldValue);
                } else {
                    System.out.println(fieldValue);
                }
            } else {
                if (item.getSize() <= 0) {
                    continue;
                }
                String contentType = item.getContentType();
                File uploadedFile = new File(item.getName());
                File savedFile = null;
                if (fieldName.equals("imagefile")) { //imagefile对应页面上input的名字
                    if (!contentType.startsWith("image")) {
                        message.append("Incorrect file uploaded! " +
                                       uploadedFile.getName() +
                                       "is not of type image."
                                );
                        continue;
                    }

                    savedFile = new File(destinationPath, uploadedFile.getName());
                    try {
                        item.write(savedFile);
                    } catch (Exception ex) {
                    }
                } else {
                    if (contentType.indexOf("msword") == -1) {
                        message.append("Incorrect File uploaded! " +
                                       uploadedFile.getName() +
                                       " is not of type Word."
                                );
                        continue;
                    }
                    savedFile = new File(destinationPath, uploadedFile.getName());
                    try {
                        item.write(savedFile);
                    } catch (Exception ex1) {
                    }
                }
            }
        }
        request.setAttribute("message", message.toString());
    }

    public String getTempPath() {
        return tempPath;
    }

    public int getSizeThreshold() {
        return sizeThreshold;
    }

    public long getSizeMax() {
        return sizeMax;
    }


    public HttpServletRequest getFileuploadRequest() {
        return fileuploadRequest;
    }

    public String getDestinationPath() {
        return destinationPath;
    }

    public StringBuffer getMessage() {
        return message;
    }

    public void setDestinationPath(String destinationPath) {
        this.destinationPath = destinationPath;
    }

    public void setFileuploadRequest(HttpServletRequest fileuploadRequest) {
        this.fileuploadRequest = fileuploadRequest;
    }


    public void setSizeMax(long sizeMax) {
        this.sizeMax = sizeMax;
    }

    public void setSizeThreshold(int sizeThreshold) {
        this.sizeThreshold = sizeThreshold;
    }

    public void setTempPath(String tempPath) {
        this.tempPath = tempPath;
    }

    public void setMessage(StringBuffer message) {
        this.message = message;
    }


}
 附录:普通文件的contentType

world: application/msword
excel: application/vnd.ms-excel
pdf: application/pdf
txt: text/plain
ppt: application/vnd.ms-powerpoint
htm: text/html

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:116926次
    • 积分:1379
    • 等级:
    • 排名:千里之外
    • 原创:14篇
    • 转载:16篇
    • 译文:0篇
    • 评论:11条
    博客专栏
    文章分类
    最新评论