JSP+Servlet中使用cos.jar实现文件上传下载
程序员文章站
2022-07-10 18:40:47
第一、前言本文通过JSP+Servlet的架构,用cos.jar实现文件的上传与下载。不涉及数据库交互。第二、引入相关jar包第三、代码示例1、新建com.servlet.UploadServlet.javaimport java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;impor...
第一、前言
本文通过JSP+Servlet的架构,用cos.jar实现文件的上传与下载。不涉及数据库交互。
第二、引入相关jar包
下载地址:JSP+Servlet+cos文件上传下载Jar包.rar
第三、代码示例
1、新建com.servlet.UploadServlet.java
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.UUID; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.oreilly.servlet.MultipartRequest; /**
* 文件上传
* @author shixiangcheng
* 2020-08-09
*/ public class UploadServlet extends HttpServlet{ private static final long serialVersionUID = 1L; 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{ request.setCharacterEncoding("UTF-8"); String batchNo=UUID.randomUUID().toString().trim(); String root=getServletContext().getRealPath("/"); MultipartRequest mr=new MultipartRequest(request, root,"UTF-8"); //可通过下面方式获取页面提交的其它字段值 //String studentNo=mr.getParameter("studentNo"); File file=mr.getFile("file"); String realFileName=file.getName(); File fileMkdir=new File("E:\\文件"); //定义输出流,将文件保存在E盘 file.getOriginalFilename()为获得文件的名字 FileOutputStream os=new FileOutputStream(fileMkdir.getPath()+"\\"+batchNo+realFileName.substring(realFileName.indexOf("."))); InputStream in=new FileInputStream(file); byte buffer[]=new byte[1024]; //判断输入流中的数据是否已经读完的标识 int len=0; //循环将输入流读入到缓冲区当中,(len=in.read(buffer))>0就表示in里面还有数据 while((len=in.read(buffer))>0){//使用FileOutputStream输出流将缓冲区的数据写入到指定的目录 os.write(buffer, 0, len); } os.flush(); //关闭流 in.close(); os.close(); request.getRequestDispatcher("/success.jsp?realFileName="+realFileName+"&fileName="+batchNo+realFileName.substring(realFileName.indexOf("."))).forward(request, response); } }
2、新建com.servlet.DownLoadServlet.java
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URLEncoder; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /**
* 文件下载
* @author shixiangcheng
* 2020-08-09
*/ public class DownLoadServlet extends HttpServlet{ private static final long serialVersionUID = -4703546973088226197L; public DownLoadServlet() { super(); } protected void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException{ doPost(request, response); } protected void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException{ request.setCharacterEncoding("UTF-8"); String fileName=request.getParameter("fileName"); String realFileName=request.getParameter("realFileName"); String path = "E:/文件/"+ fileName; BufferedInputStream bis = null; BufferedOutputStream bos = null; OutputStream fos = null; InputStream fis = null; File uploadFile = new File(path); try { fis = new FileInputStream(uploadFile); bis = new BufferedInputStream(fis); fos =response.getOutputStream(); bos = new BufferedOutputStream(fos); //这个就就是弹出下载对话框的关键代码 response.setHeader("Content-disposition","attachment;filename="+URLEncoder.encode(realFileName,"UTF-8")); byte[] buffer = new byte[1024]; //判断输入流中的数据是否已经读完的标识 int len = 0; //循环将输入流读入到缓冲区当中,(len=in.read(buffer))>0就表示in里面还有数据 while((len=bis.read(buffer))>0){ bos.write(buffer, 0, len); } bos.flush(); } catch (Exception e) { e.printStackTrace(); }finally { if(fis!=null) fis.close(); if(bis!=null) bis.close(); if(fos!=null) fos.close(); if(bos!=null) bos.close(); } } }
3、修改web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <servlet> <description></description> <display-name>UploadServlet</display-name> <servlet-name>UploadServlet</servlet-name> <servlet-class>com.servlet.UploadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UploadServlet</servlet-name> <url-pattern>/UploadServlet</url-pattern> </servlet-mapping> <servlet> <description></description> <display-name>DownLoadServlet</display-name> <servlet-name>DownLoadServlet</servlet-name> <servlet-class>com.servlet.DownLoadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>DownLoadServlet</servlet-name> <url-pattern>/DownLoadServlet</url-pattern> </servlet-mapping> </web-app>
4、新建index.jsp
<%@page contentType="text/html;charset=utf-8" %> <html> <head> <title>上传</title> <style type="text/css"> table {font-size:18px;} table caption {font-size:30px;} </style> <script type="text/javascript"> function checkForm(myForm) { if(myForm.file.value == "") { alert("附件不能为空!"); myForm.file.focus(); return false; } return true; } </script> </head> <body> <form action="<%=request.getContextPath()%>/UploadServlet" name="form1" method="post" onsubmit="return checkForm(this);" enctype="multipart/form-data"> <table border="1" align="center"> <caption>文件上传</caption> <tr> <td>文件<font color="red">*</font></td> <td><input type="file" name="file" id="file" style="width:400px;"/></td> </tr> <tr> <td colspan="2" align="center"> </td> </tr> <tr> <td colspan="2" align="center"> <input type="submit" value="提交" style="width:100px;"> </td> </tr> </table> </form> </body> </html>
5、新建success.jsp
<%@page contentType="text/html;charset=utf-8" %> <% String realFileName=request.getParameter("realFileName"); String fileName=request.getParameter("fileName"); %> <html> <head> <title>下载</title> </head> <body> <span>上传成功!</span> <a href="<%=request.getContextPath() %>/DownLoadServlet?realFileName=<%=realFileName%>&fileName=<%=fileName%>">下载</a> <a href="javascript:history.go(-1);">返回</a> </body> </html>
6、运行
第一、选择文件,然后点击提交
第二、提交成功后,到下面页面,点击下载,可下载上传的文件。
第三、文件上传后存在硬盘上。
欢迎大家积极留言交流学习心得,点赞的人最美丽,谢谢!
本文地址:https://blog.csdn.net/xiaoxiaodaxiake/article/details/107891957
推荐阅读
-
使用springboot实现文件下载时文件名中的中文变成下划线
-
使用smartupload组件实现jsp+jdbc上传下载文件实例解析
-
使用Python下载歌词并嵌入歌曲文件中的实现代码
-
CentOS中使用Shell脚本实现每天自动备份网站文件和数据库并上传到FTP中
-
使用Bash Shell对目录中的文件实现递归式拷贝
-
Jsp+Servlet实现文件上传下载 文件列表展示(二)
-
Jsp+Servlet实现文件上传下载 删除上传文件(三)
-
Jsp+Servlet实现文件上传下载 文件上传(一)
-
Effective Modern C++ 条款22 当使用Pimpl Idiom时,在实现文件中定义特殊成员函数
-
使用PHP实现下载CSS文件中的图片