你的位置:首页 > Java教程

[Java教程]利用 cos 组件实现jsp中附件上传


下载cos组件并安装到web工程

1、访问 http://www.servlets.com/

3、点击 cos-26Dec2008.zip 下载组件

5、复制到工程中的lib下

6、重启web工程

 

制作jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>文件上传demo</title><link href="http://www.cnblogs.com//web01//css/main.css" rel="stylesheet" type="text/css" /></head><%@ include file="top.jsp" %><body>  <form action="handleFileUpload.jsp" name="frm1" method="post" enctype="multipart/form-data">    文件名:<input type="file" name="file1" size="50"><br>    <input type="submit" value="上传">  </form></body><%@ include file="bottom.jsp" %></html>

 

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@ page import="com.oreilly.servlet.MultipartRequest" %><%@ page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy" %><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>文件上传demo</title><link href="http://www.cnblogs.com//web01//css/main.css" rel="stylesheet" type="text/css" /></head><%@ include file="top.jsp" %><body><%  String savePath = "d:/test/uploadfile/";  int sizeLimit = 30 * 1024 * 1024;  String formName = "";  String fileName = "";  long fileSize = 0;    MultipartRequest multi = new MultipartRequest(request, savePath, sizeLimit, "UTF-8", new DefaultFileRenamePolicy());    Enumeration formNames = multi.getFileNames();  while (formNames.hasMoreElements()) {    formName = (String) formNames.nextElement();    fileName = multi.getFilesystemName(formName);        if (fileName != null) {      fileSize = multi.getFile(formName).length();    }  }  out.println("文件上传成功!<br>");  out.println("文件名:" + fileName + "<br>");  out.println("文件大小:" + fileSize / 1024 + "KB");%></body><%@ include file="bottom.jsp" %></html>

 

测试上传工程