关于jsp jsp实现文件上传下载。

向西向远方
JSP上传文件
创建文件上传表单
接下来我们使用HTML标签来创建文件上传表单,以下为要注意的点:
form表单 method 属性必须设置为 POST 方法 ,不能使用 GET 方法。
form表单 enctype 属性需要设置为 multipart/form-data。
form表单 action 属性需要设置为提交到后台处理文件上传的jsp文件地址。例如 uploadFile.jsp 程序文件用来处理上传的文件。
上传文件元素需要使用 &input .../& 标签,属性设置为 type="file"。如果需要上传多个文件,可以在 &input .../&标签中设置不同的名称。
以下是一个上传文件的表单,实例如下:
File Uploading Form
File Upload:
Select a file to upload:
action="UploadServlet" method="post"
enctype="multipart/form-data"
type="file" name="file" size="50"
type="submit" value="Upload File"
在你本地浏览器访问该文件,显示界面如下所示,在你点击"Upload File"会弹出一个窗口让你选择要上传的文件:
后台JSP处理脚本
首先我们先定义文件上传后存储在服务上的位置,你可以将路径写在你的程序当中,或者我们可以在web.xml配置文件中通过设置 context-param 元素来设置文件存储的目录,如下所示:
Location to store uploaded file
file-upload
c:\apache-tomcat-5.5.29\webapps\data\
以下脚本文件UploadFile.jsp可以处理多个上传的文件,在使用该脚本前,我们需要注意以下几点:
以下实例依赖 FileUpload, 所以你需要在你的classpath中引入最新的 commons-fileupload.x.x.jar 包文件。 下载地址为:。
FileUpload 依赖 Commons IO, 所以你需要在你的classpath中引入最新的 commons-io-x.x.jar 。 下载地址为:。
在测试以下实例时,你需要上传确认上传的文件大小小于 maxFileSize 变量设置的大小 ,否则文件无法上传成功。
确保你已经创建了目录 c:\temp 和 c:\apache-tomcat-5.5.29\webapps\data 。&%@ page import="java.io.*,java.util.*, javax.servlet.*" %&
&%@ page import="javax.servlet.http.*" %&
&%@ page import="org.apache.commons.fileupload.*" %&
&%@ page import="org.apache.commons.fileupload.disk.*" %&
&%@ page import="org.apache.commons.fileupload.servlet.*" %&
&%@ page import="org.apache.commons.io.output.*" %&
File file ;
int maxFileSize = 5000 * 1024;
int maxMemSize = 5000 * 1024;
ServletContext context = pageContext.getServletContext();
String filePath = context.getInitParameter("file-upload");
// 验证上传内容了类型
String contentType = request.getContentType();
if ((contentType.indexOf("multipart/form-data") &= 0)) {
DiskFileItemFactory factory = new DiskFileItemFactory();
// 设置内存中存储文件的最大值
factory.setSizeThreshold(maxMemSize);
// 本地存储的数据大于 maxMemSize.
factory.setRepository(new File("c:\\temp"));
// 创建一个新的文件上传处理程序
ServletFileUpload upload = new ServletFileUpload(factory);
// 设置最大上传的文件大小
upload.setSizeMax( maxFileSize );
// 解析获取的文件
List fileItems = upload.parseRequest(request);
// 处理上传的文件
Iterator i = fileItems.iterator();
out.println("&html&");
out.println("&head&");
out.println("&title&JSP File upload&/title&");
out.println("&/head&");
out.println("&body&");
while ( i.hasNext () )
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () )
// 获取上传文件的参数
String fieldName = fi.getFieldName();
String fileName = fi.getName();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// 写入文件
if( fileName.lastIndexOf("\\") &= 0 ){
file = new File( filePath ,
fileName.substring( fileName.lastIndexOf("\\"))) ;
file = new File( filePath ,
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
fi.write( file ) ;
out.println("Uploaded Filename: " + filePath +
fileName + "&br&");
out.println("&/body&");
out.println("&/html&");
}catch(Exception ex) {
System.out.println(ex);
out.println("&html&");
out.println("&head&");
out.println("&title&Servlet upload&/title&");
out.println("&/head&");
out.println("&body&");
out.println("&p&No file uploaded&/p&");
out.println("&/body&");
out.println("&/html&");
接下来让我们通过浏览器访问 http://localhost:8080/UploadFile.htm,界面如下所示,并上传文件:
如果你的JSP脚本运行正常,文件将被上传至 c:\apache-tomcat-5.5.29\webapps\data\ ,你可以打开文件夹看看是否上传成功。
没有更多推荐了,
加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!一步一个脚印
servlet+jsp实现的文件上传与下载
java文件上传与下载
通过微表单元苏设置Method = "post"
enctype = "multipart/form-data"属性,让表单提交的数据以二进制编码的方式提交,在接收此请求的Servlet
中用二进制流来获取内容,就可以取得上传文件的内容,从而实现文件的上传。
表单ENCTYPE属性
application/x-www-form-urlencoded :这是默认的编码方式,它只处理表单域里的value属性值。采用这种编码方式的表单会将表单域的值处理成URL编码方式multipart/form-data:这种编码方式的表单会以二进制流的方式来处理表单数据,这种编码方式会把文件域指定文件的内容也封装到请求参数里text/plain:这种方式主要适用于直接通过表单发送邮件的方式
需要通过HttpServletResponse.setContentType方法设置Content-Type头字段的值,
为浏览器无法使用某种方式或激活某个程序来处理的MIME类型
需要通过HttpServletResponse.setHeader方法设置Content-Disposition头的值为
“filename=文件名”;
读取下载文件,调用HttpServletResponse.getOutputStream方法返回的ServletOutputStream
对象来向客户端写入附件文件内容
文件上传实现步骤
获取request当中的流信息,保存到临时文件从临时文件当中得到上传的文件名,及文件内容起止位置
根据文件起止位置,读取上传文件内容,保存到本地
&form action="uploadServlet.do" method="post"
enctype="multipart/form-data"&
&input id="myfile" name="myfile" type="file"
/& &input type="submit" value="提交" /&${result}
&a href="downloadServlet.do?filename=test1.txt"&test1.txt&/a&
${errorResult}
public class UploadServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req,resp);
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//从request当中获取流信息
InputStream fileSource = req.getInputStream();
String tempFileName = "E:/tempFile";
//tempFile指向临时文件
File tempFile = new File(tempFileName);
//outputStram文件输出流指向这个临时文件
FileOutputStream outputStream = new FileOutputStream(tempFile);
byte b[] = new byte[1024];
while(( n = fileSource.read(b)) != -1){
outputStream.write(b, 0, n);
//关闭输出流、输入流
outputStream.close();
fileSource.close();
//获取上传文件的名称
RandomAccessFile randomFile = new RandomAccessFile(tempFile,"r");
l = new String(l.getBytes("8859_1"),"gbk");
String str2 = randomFile.readLine();
//编码转换
str2 = new String(str2.getBytes("8859_1"),"utf-8");
System.out.println(str2);
String str = randomFile.readLine();
str = new String(str.getBytes("8859_1"),"utf-8");
System.out.println(str);
int beginIndex = str.lastIndexOf("=") + 2;
int endIndex = str.lastIndexOf("\"");
String filename = str.substring(beginIndex, endIndex);
System.out.println("filename:" + filename);
//重新定位文件指针到文件头
randomFile.seek(0);
long startPosition = 0;
int i = 1;
//获取文件内容 开始位置
while(( n = randomFile.readByte()) != -1 && i &=4){
if(n == '\n'){
startPosition = randomFile.getFilePointer();
startPosition = randomFile.getFilePointer() -1;
//获取文件内容 结束位置
randomFile.seek(randomFile.length());
long endPosition = randomFile.getFilePointer();
int j = 1;
while(endPosition &=0 && j&=2){
endPosition--;
randomFile.seek(endPosition);
if(randomFile.readByte() == '\n'){
endPosition = endPosition -1;
//设置保存上传文件的路径
//路径可以自行设置
String realPath = "E:\\myeclipse workplace\\css+js";
String realPath = getServletContext().getRealPath("/") + "images";
File fileupload = new File(realPath);
System.out.println(realPath);
if(!fileupload.exists()){
fileupload.mkdir();
File saveFile = new File(realPath,filename);
RandomAccessFile randomAccessFile = new RandomAccessFile(saveFile,"rw");
//从临时文件当中读取文件内容(根据起止位置获取)
randomFile.seek(startPosition);
while(startPosition & endPosition){
randomAccessFile.write(randomFile.readByte());
startPosition = randomFile.getFilePointer();
//关闭输入输出流、删除临时文件
randomAccessFile.close();
randomFile.close();
tempFile.delete();
req.setAttribute("result", "上传成功!");
RequestDispatcher dispatcher = req.getRequestDispatcher("test.jsp");
dispatcher.forward(req, resp);
public class DownLoadServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/charset=utf-8");
req.setCharacterEncoding("utf-8");
resp.setContentType("text/charset=UTF-8");
resp.setContentType("text/plain");
//进行编码的转换,因为不能识别中文
resp.setHeader("content-type","text/charset=UTF-8");
String path = getServletContext().getRealPath("/") + "images/";
String fileName = req.getParameter("filename");
String filename =
filename = new String(fileName.getBytes("8859_1"),"utf-8");
filename = new String(filename.getBytes("8859_1"),"uft-8");
System.out.println("路径:" + path + "文件名:" + filename);
File file = new File(path + filename);
if (file.exists()) {
//由于下载的时候与浏览器的编码不符,浏览器不能识别中文编码,这里要进行转换
String value = new String(filename.getBytes("utf-8"),"ISO-8859-1");
resp.setContentType("application/x-msdownload");
resp.setHeader("Content-Disposition", "filename=\""
+ value + "\"");
InputStream inputStream = new FileInputStream(file);
ServletOutputStream outputStream = resp.getOutputStream();
byte b[] = new byte[1024];
while ((n = inputStream.read(b)) != -1) {
outputStream.write(b, 0, n);
outputStream.close();
inputStream.close();
req.setAttribute("errorResult", "文件不存在下载失败!!");
resp.sendRedirect("luntan.jsp");
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
没有更多推荐了,
加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!jsp上传文件fileupload
我的图书馆
jsp上传文件fileupload
本教程以Apache组织的commons项目中的FileUpload项目做为jsp的文件上传组件,FileUpload项目完全尊守RFC1867规范中关于在HTTP request 中通过Post方法提交文件的规范,该项目性能稳定快速,易于部署和使用.本次教程以前端jsp + 后端 servlet的方式上传文件,你也可以完全在jsp中实现而不用servlet.在开始之前你要准备以下几个东西:1. commons-FileUpload 1.2 包&& 下载地址:2. commons-IO 1.3.1 包&& 下载地址:3. Commons-BeanUtils 1.7 包&& 下载地址:&有了上面这些东西我们就可以开始了===============================================================================1. 新建一个叫upload的WEB项目(我用的是Lomboz3.2开发环境)2. 把上面下载下来的包分别解压并拷贝*.jar的文件到上面那个项目的WEB-INF/lib目录中3.接下来我们要准备一份如下内容的upload.jsp文件,用来选择要上传的文件,&html&&head&&title&Jsp+Servlet upload file&/title&&/head&&body&& &form name="upform" action="UploadServlet" method="POST" enctype="multipart/form-data"&& & &input type ="file" name="file1" id="file1"/&&br/&& & &input type ="file" name="file2" if="file2"/&&br/&& & &input type ="file" name="file3" id="file3"/&&br/&& & &input type="submit" value="Submit" /&&br/&& & &input type="reset" /&& &/form&&/body&&/html&上面文件中有几个需要注意的地方就是1. action="UploadServlet" 必须和后面的web.xml配置文件中对servlet映射必须保持一致.2. method="POST" 这里必须为"POST"方式提交不能是"GET".3. enctype="multipart/form-data" 这里是要提交的内容格式,表示你要提交的是数据流,而不是普通的表单文本.4. file1,file2,file3表示你要3个文件一起上传,你也可以一次只上传一个文件.===================================================================================接下来我们要写一个与上面这个upload.jsp配套的servlet程序,就叫做UploadServlet.java吧以下是该servlet的详细代码:看上去有点长,不过并不复杂,很容易明白的.import java.io.BufferedInputSimport java.io.BufferedOutputSimport java.io.Fimport java.io.FileOutputSimport java.io.IOEimport javax.servlet.ServletEimport javax.servlet.http.HttpServletRimport javax.servlet.http.HttpServletRimport org.apache.commons.fileupload.DefaultFileItemFimport org.apache.commons.fileupload.FileItemFimport org.apache.commons.fileupload.FileItemIimport org.apache.commons.fileupload.FileItemSimport org.apache.commons.fileupload.disk.DiskFileItemFimport org.apache.commons.fileupload.servlet.ServletFileUimport org.apache.commons.fileupload.util.S/*** Servlet implementation class for Servlet: UploadServlet**/public class UploadServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {& & File tmpDir =//初始化上传文件的临时存放目录& & File saveDir =//初始化上传文件后的保存目录& public UploadServlet() {& & super();& } & && protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {& & doPost(request,response);& } & &&&&& protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {& & try{& & & & if(ServletFileUpload.isMultipartContent(request)){& & & & & DiskFileItemFactory dff = new DiskFileItemFactory();//创建该对象& & & & & dff.setRepository(tmpDir);//指定上传文件的临时目录& & & & & dff.setSizeThreshold(1024000);//指定在内存中缓存数据大小,单位为byte& & & & & ServletFileUpload sfu = new ServletFileUpload(dff);//创建该对象& & & & & sfu.setFileSizeMax(5000000);//指定单个上传文件的最大尺寸& & & & & sfu.setSizeMax();//指定一次上传多个文件的总尺寸& & & & & FileItemIterator fii = sfu.getItemIterator(request);//解析request 请求,并返回FileItemIterator集合& & & & & while(fii.hasNext()){& & & & & & FileItemStream fis = fii.next();//从集合中获得一个文件流& & & & & & if(!fis.isFormField() && fis.getName().length()&0){//过滤掉表单中非文件域& & & & & & & & String fileName = fis.getName().substring(fis.getName().lastIndexOf("\\"));//获得上传文件的文件名& & & & & & & & BufferedInputStream in = new BufferedInputStream(fis.openStream());//获得文件输入流& & & & & & & & BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(saveDir+fileName)));//获得文件输出流& & & & & & & & Streams.copy(in, out, true);//开始把文件写到你指定的上传文件夹& & & & & & }& & & & & }& & & & & response.getWriter().println("File upload successfully!!!");//终于成功了,还不到你的上传文件中看看,你要的东西都到齐了吗& & & & }& & }catch(Exception e){& & & & e.printStackTrace();& & }& } & & & & && public void init() throws ServletException {& & /* 对上传文件夹和临时文件夹进行初始化& & *& & */& & super.init();& & & String tmpPath = "c:""tmpdir";& & & String savePath = "c:""updir";& & tmpDir = new File(tmpPath);& & saveDir = new File(savePath);& & if(!tmpDir.isDirectory())& & & & tmpDir.mkdir();& & if(!saveDir.isDirectory())& & & & saveDir.mkdir();& &&& } &&}========================================================================================================upload.jsp文件有了,配套的servlet也有了,现在最后剩下的就是怎么让它们配合工作了,接着我们把WEB-INF/web.xml文件请出来,并在该文件中加入以下内容:& &servlet&& & &servlet-name&UploadServlet&/servlet-name&& & &servlet-class&UploadServlet&/servlet-class&& &/servlet&& &servlet-mapping&& & &servlet-name&UploadServlet&/servlet-name&& & &url-pattern&/UploadServlet&/url-pattern&& &/servlet-mapping&写好以后再点击"保存"
[转]&[转]&[转]&[转]&
喜欢该文的人也喜欢豆丁微信公众号
君,已阅读到文档的结尾了呢~~
扫扫二维码,随身浏览文档
手机或平板扫扫即可继续访问
怎样用jsp实现一个文件夹下的所有文件上传啊解决办法
举报该文档为侵权文档。
举报该文档含有违规或不良信息。
反馈该文档无法正常浏览。
举报该文档为重复文档。
推荐理由:
将文档分享至:
分享完整地址
文档地址:
粘贴到BBS或博客
flash地址:
支持嵌入FLASH地址的网站使用
html代码:
&embed src='http://www.docin.com/DocinViewer-4.swf' width='100%' height='600' type=application/x-shockwave-flash ALLOWFULLSCREEN='true' ALLOWSCRIPTACCESS='always'&&/embed&
450px*300px480px*400px650px*490px
支持嵌入HTML代码的网站使用
您的内容已经提交成功
您所提交的内容需要审核后才能发布,请您等待!
3秒自动关闭窗口jsp文件上传什么是普通字段和文件字段_百度知道
jsp文件上传什么是普通字段和文件字段
如题:最好用例子说明
我有更好的答案
jsp中的上传:有FORM表单的enctype属性设置为“multipart/form-data”,method属性设置为“post”即可,下面是我们文件上传页面的表单代码:&form action=&&%=request.getContextPath()%&/servlet/SimpleUpload& enctype=&multipart/form-data& method=&post&&文本1:&input type=&text& name=&text1& value=&文本1&&&br&文件2:&input type=&text& name=&text2& value=&文本2&&&br&文件1:&input type=&file& name=&file1&&&br&文件2:&input type=&file& name=&file2&&&br&文件3:&input type=&file& name=&file3&&&br&&input type=&submit& value=&开始上传&&&/form&其中:文本1和文本2是普通字段,文件1、文件2和文件3是文件字段。
【0元入学,两周免费试听】
主营:培训【Python+人工智能,Java大数据,HTML5】
为您推荐:
其他类似问题
文件上传的相关知识
换一换
回答问题,赢新手礼包
个人、企业类
违法有害信息,请在下方选择后提交
色情、暴力
我们会通过消息、邮箱等方式尽快将举报结果通知您。

我要回帖

更多关于 jsp实现文件上传 的文章

 

随机推荐