上传文件的两种:
·第一种:上传到数据库中保存;
|-如果上传的内容大的话,这种方式不方便;
·第二种:上传到Web根目录种的某个文件夹中保存;
|-可以上传较大的内容;
下面例子是使用第二种方法:smartUpload
Smarupload01.html
<html> <head> <title>smartupload</title> </head> <body> <form action="smartupload01.jsp" method="post" enctype="multipart/form-data">//封装MIME类型 用户姓名:<input type="text" name="uname"><br> 上传的图片:<input type="file" name="pic"><br> <input type="submit" value="上传"> </form> </body> </html> |
smartupload01.jsp
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%> <jsp:useBean id="smartupload" class="org.lxh.smart.SmartUpload"/> <html> <head> <title>smartupload</title> </head> <body> <% request.setCharacterEncoding("GBK") ; smartupload.initialize(pageContext) ; // 初始化上传 smartupload.upload() ; // 准备上传 String name = smartupload.getRequest().getParameter("uname") ;//因为封装了MIME类型后,不能直接利用request来接受参数了,必须通过smartupload提供 的getRequest来代替request smartupload.save("upload") ; // 保存WEB根目录下的upload文件 %> <h1><%=name%></h1> </body> </html> |
改善上面的代码, 使得可以保存时候给文件定义一个名字;
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%> <jsp:useBean id="smartupload" class="org.lxh.smart.SmartUpload"/> <html> <head> <title>smartupload</title> </head> <body> <% request.setCharacterEncoding("GBK") ; smartupload.initialize(pageContext) ; // 初始化上传 smartupload.upload() ; // 准备上传 String name = smartupload.getRequest().getParameter("uname") ; name = name + "." + smartupload.getFiles().getFile(0).getFileExt() ; String fileName = this.getServletContext().getRealPath("/") + "upload/" + name ; smartupload.getFiles().getFile(0).saveAs(fileName) ;//给文件定义一个名字,使得上传上去的文件不会出现同名而覆盖。 %> </body> </html> |