jsp实现文件上传下载功能

当初学习Javaweb时做的小demo,没想到有许多小伙伴可以刷到,如果对你有帮助的话,帮忙Star一下,

源码已放到码云上:https://gitee.com/zhongxia621/mywebproject

文件上传首先得引入两个jar包,建议在mvn库中下载,下载完粘贴到lib目录下

首先写上传文件的jsp界面

<form action="UpLoadServet" method="post" enctype="multipart/form-data">
<font color="white" size="5px">文件上传功能(将你的照片,音乐,视频或者文档等经过上传分享到我的电脑)</font><br><br>
学号:<input name="sno"><br><br>
姓名:<input name="sname"><br><br>
上传文件:<input type="file" name="spicture"><br><br>
<input type="submit" value="上传"><br><br>
<font color="white" size="5px">文件下载功能(可以下载我在tomcat服务器上传的文件)</font><br><br>
</form>

接下来写上传功能的Servlet(主要就是重写它的doget方法,首先将请求,响应编码设为utf-8,接下来判断提交数据是否为表单数据,接下来创建文件上传解析对象,返回一个list集合,然后迭代器遍历,获取文件名称,最后创建你要保存的路径,调用write方法写入自己电脑)

package com.student.servlet;

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

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class UpLoadServet
 */
public class UpLoadServet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UpLoadServet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=UTF-8");
		boolean isMultipart=ServletFileUpload.isMultipartContent(request);
		if(isMultipart)
		{
			FileItemFactory factory=new DiskFileItemFactory();
			ServletFileUpload upload=new ServletFileUpload(factory);
			try {
				List<FileItem> items=upload.parseRequest(request);
				Iterator<FileItem> it = items.iterator();
				while(it.hasNext())
				{
					FileItem item = it.next();
					String itemname = item.getFieldName();
					int sno=-1;
					String sname=null;
					
					if(item.isFormField())
					{
						if(itemname.equals("sno"))
						{
							sno=Integer.parseInt(item.getString("utf-8"));
						}else if(itemname.equals("sname"))
						{
							sname=item.getString("utf-8");
							sname=item.getName();
						}else
						{
							System.out.println("其他字段");
						}
					}else
					{
						String filename=item.getName();
						//String path=request.getSession().getServletContext().getRealPath("upload");
						String path="E:\\upload";
						File file=new File(path,filename);
						item.write(file);
						request.setAttribute("news", filename+"上传成功,谢谢分享");
						request.getRequestDispatcher("print.jsp").forward(request, response);
						//System.out.println(filename+"上传成功!!!");
						return;
					}
					
				}
			} catch (FileUploadException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

效果:

上传成功后去我的E盘upload目录下去检查:

文件上传功能对于文件类型大小没有限制,如果要想设置格式的话建议直接substring方法获取.之后的字母,判断是什么类型,还有maxsize方法控制上传文件大小。

 

接下来实现文件下载功能,这个不需要jar包

主要思路:

客户端请求servlet,servlet通过文件地址,将文件转为输入流,读到Servlet中,通过输出流将文件输出给用户

首先写文件下载jsp界面(可以通过获取文件夹目录方便,以后有待优化)

<font color="white" size="5px">文件下载功能(可以下载我在tomcat服务器上传的文件)</font><br><br>
</form>
<font color="#B2DFEE" size="5px">tomcat服务器文件</font><br><br>
<a href="DownLoadServlet?filename=测试.txt"><font color="green" size="4px">测试文档</font></a><br>
<a href="DownLoadServlet?filename=1.jpg"><font color="green" size="4px">照片1</font></a><br>
<a href="DownLoadServlet?filename=2.jpg"><font color="green" size="4px">照片2</font></a><br>
<a href="DownLoadServlet?filename=3.jpg"><font color="green" size="4px">照片3</font></a><br>
<a href="DownLoadServlet?filename=4.jpg"><font color="green" size="4px">照片4</font></a><br><br>
<a href="zhuce.jsp"><font color="white" size="5px">点此回到首页</font></a>

效果:

接下来写下载的Servlet(首先获取filename,然后通过获取user-agent字符串来了解用户是通过什么浏览器访问从而解决中文乱码问题,我只写了个谷歌和IE浏览器的,接下来就是将文件地址转为输入流,服务端响应转为输出流给用户,)

package com.student.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



/**
 * Servlet implementation class DownLoadServlet
 */
public class DownLoadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DownLoadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	String filename = request.getParameter("filename");	
	response.addHeader("content-Type", "application/octet-stream");
	
	String agent = request.getHeader("User-Agent");
	
	 if(agent.toLowerCase().indexOf("chrome")>0)
	{
		response.addHeader("content-Disposition", "attachment;filename="+new String(filename.getBytes("UTF-8"), "ISO8859-1"));
	}
	else
	{
		response.addHeader("content-Disposition", "attachment;filename="+URLEncoder.encode(filename, "UTF-8"));
	}
	InputStream in = getServletContext().getResourceAsStream("/download/"+filename);
	ServletOutputStream out = response.getOutputStream();
	byte[] bs=new byte[1024];
	int len=-1;
	while((len=in.read(bs))!=-1)
	{
		out.write(bs,0,len);
	}
	out.close();
	in.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

文件下载效果:

差不多就写完了,感觉上传下载还有方面需要进一步优化,有待更新。

 

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 创作都市 设计师:CSDN官方博客 返回首页