javaweb文件下载与文件上传

javaweb文件下载与文件上传

狂神视频讲解

文件下载

步骤

 1.获取要下载文件的路径
2.下载的文件名是啥?
3.设置想办法让浏览器能够支持(Content-Disposition)下载我们需要的东西,中文文件名用URLEncoder.encode进行转码,否则有可能乱码;
4.获取下载文件的输入流
5.创建缓冲区
6.获取OutputStream对象
7.将FileOutputStream流写入到buffer缓冲区,使用OutputSteam将缓冲区中的数据输出到客户端
public class FileServlet extends HttpServlet {
   @Override
   protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
   //   1.获取要下载文件的路径
       String realPath = "D:\\IdeaProject\\helloServlet\\hello-02\\target\\classes\\你好.png";
       System.out.println("下载文件的路径:"+realPath);
   //   2.下载的文件名是啥?
       String filename = realPath.substring(realPath.lastIndexOf("\\") + 1);
       //   3.设置想办法让浏览器能够支持(Content-Disposition)下载我们需要的东西,中文文件名用URLEncoder.encode进行转码,否则有可能乱码;
       resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(filename,"utf-8"));
   //   4.获取下载文件的输入流
       FileInputStream in = new FileInputStream(realPath);
       //   5.创建缓冲区
       int len=0;
       byte[] buffer = new byte[1024];
       //   6.获取OutputStream对象
       ServletOutputStream out = resp.getOutputStream();
       //   7.将FileOutputStream流写入到buffer缓冲区,使用OutputSteam将缓冲区中的数据输出到客户端
       while((len=in.read(buffer))>0){
           out.write(buffer,0,len);
      }
       in.close();
       out.close();
  }

文件上传

  1. 准备工作

    jar包准备

    common-fileupload

    common-io(common-fileupload是依赖于common-io这个包的,所以还需要下载这个包。 )

     <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
           <dependency>
               <groupId>commons-fileupload</groupId>
               <artifactId>commons-fileupload</artifactId>
               <version>1.3.3</version>
           </dependency>
           <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
           <dependency>
               <groupId>commons-io</groupId>
               <artifactId>commons-io</artifactId>
               <version>2.7</version>
           </dependency>

     

  2. 文件上传的细节

  上述的代码虽然可以成功将文件上传到服务器上面的指定目录当中,但是文件上传功能有许多需要注意的小细节问题,以下列出的几点需要特别注意的:

  (1)为保证服务器安全,上传文件应该放在外界无法直接访问的目录下,比如放于WEB-INF目录下。

  (2)为防止文件覆盖的现象发生,要为上传文件产生一个唯一的文件名。(加后缀:时间戳、uuid)

  (3)为防止一个目录下面出现太多文件,要使用hash算法打散存储。

  (4)要限制上传文件的最大值。

  (5)要限制上传文件的类型,在收到上传文件名时,判断后缀名是否合法。

  1. 需要用到的类详解

    ServletFileUpload负责处理上传的文件数据,并将表单中的每个输入项封装成一个FileItem对象,在使用ServletFileUpload对象解析请求时需要DiskFileItemFactory对象。所以,我们需要在进行解析工作前构造好DiskFileItemFactory对象,通过ServletFileUpload对象的构造方法或者setFileItemFactory()方法设置ServletFileUpload的fileItemFactory属性。

 

 

 

FileItem

上传文件input必须有 name <input type="file" name="filename">

jsp页面: 表单如果包含一个文件上传输入项的话,这个表单一定要指定enctype属性为multipart/form-data,

提交方法为post ;因为get上传文件大小有限制,post没有限制;

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
 <head>
   <title>$Title$</title>
 </head>
 <body>
<form action="${pageContext.request.contextPath}/upload.do" method="post" enctype="multipart/form-data">
  上传用户:<input type="text" name="username"></br>
  <p><input type="file" name="file1"></p>
<p><input type="file" name="file2"></p>
<p><input type="submit"> </p>
</form>
 </body>
</html>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                     http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
        version="3.1"
        metadata-complete="true">
   <servlet>
       <servlet-name>FileServlet</servlet-name>
       <servlet-class>com.bxb.servlet.FileServlet</servlet-class>
   </servlet>
   <servlet-mapping>
       <servlet-name>FileServlet</servlet-name>
       <url-pattern>/upload.do</url-pattern>
   </servlet-mapping>
</web-app>

FileServlet

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

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.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileSerlvet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// 判断上传的文件普通表单还是带文件的表单
if (!ServletFileUpload.isMultipartContent(request)) {
return;//终止方法运行,说明这是一个普通的表单,直接返回
}
   //创建上传文件的保存路径,建议在WEB-INF路径下,安全,用户无法直接访间上传的文件;
   String uploadPath =this.getServletContext().getRealPath("/WEB-INF/upload");
   File uploadFile = new File(uploadPath);
   if (!uploadFile.exists()){
   uploadFile.mkdir(); //创建这个月录
  }

// 创建上传文件的保存路径,建议在WEB-INF路径下,安全,用户无法直接访问上传的文件
String tmpPath = this.getServletContext().getRealPath("/WEB-INF/tmp");
File file = new File(tmpPath);
if (!file.exists()) {
file.mkdir();//创建临时目录
}

// 处理上传的文件,一般都需要通过流来获取,我们可以使用 request, getInputstream(),原生态的文件上传流获取,十分麻烦
// 但是我们都建议使用 Apache的文件上传组件来实现, common-fileupload,它需要旅 commons-io组件;
try {
// 创建DiskFileItemFactory对象,处理文件路径或者大小限制
DiskFileItemFactory factory = getDiskFileItemFactory(file);
/*
* //通过这个工厂设置一个缓冲区,当上传的文件大于这个缓冲区的时候,将他放到临时文件 factory.setSizeThreshold(1024 *
* 1024); //缓存区大小为1M factory.setRepository (file);//临时目录的保存目录,需要一个File
*/

// 2、获取ServletFileUpload
ServletFileUpload upload = getServletFileUpload(factory);

// 3、处理上传文件
// 把前端请求解析,封装成FileItem对象,需要从ServletFileUpload对象中获取
String msg = uploadParseRequest(upload, request, uploadPath);

// Servlet请求转发消息
System.out.println(msg);
if(msg == "文件上传成功!") {
// Servlet请求转发消息
request.setAttribute("msg",msg);
request.getRequestDispatcher("info.jsp").forward(request, response);
}else {
msg ="请上传文件";
request.setAttribute("msg",msg);
request.getRequestDispatcher("info.jsp").forward(request, response);
}

} catch (FileUploadException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}

public static DiskFileItemFactory getDiskFileItemFactory(File file) {
DiskFileItemFactory factory = new DiskFileItemFactory();
// 通过这个工厂设置一个缓冲区,当上传的文件大于这个缓冲区的时候,将他放到临时文件中;
factory.setSizeThreshold(1024 * 1024);// 缓冲区大小为1M
factory.setRepository(file);// 临时目录的保存目录,需要一个file
return factory;
}

   
   
public static ServletFileUpload getServletFileUpload(DiskFileItemFactory factory) {
ServletFileUpload upload = new ServletFileUpload(factory);
// 监听长传进度
upload.setProgressListener(new ProgressListener() {

// pBYtesRead:已读取到的文件大小
// pContextLength:文件大小
public void update(long pBytesRead, long pContentLength, int pItems) {
System.out.println("总大小:" + pContentLength + "已上传:" + pBytesRead);
}
});

// 处理乱码问题
upload.setHeaderEncoding("UTF-8");
// 设置单个文件的最大值
upload.setFileSizeMax(1024 * 1024 * 10);
// 设置总共能够上传文件的大小
// 1024 = 1kb * 1024 = 1M * 10 = 10м

return upload;
}

   
   
public static String uploadParseRequest(ServletFileUpload upload, HttpServletRequest request, String uploadPath)
throws FileUploadException, IOException {

String msg = "";

// 把前端请求解析,封装成FileItem对象
List<FileItem> fileItems = upload.parseRequest(request);
for (FileItem fileItem : fileItems) {
if (fileItem.isFormField()) {// 判断上传的文件是普通的表单还是带文件的表单
// getFieldName指的是前端表单控件的name;
String name = fileItem.getFieldName();
String value = fileItem.getString("UTF-8"); // 处理乱码
System.out.println(name + ": " + value);
} else {// 判断它是上传的文件

// ============处理文件==============

// 拿到文件名
String uploadFileName = fileItem.getName();
System.out.println("上传的文件名: " + uploadFileName);
if (uploadFileName.trim().equals("") || uploadFileName == null) {
continue;
}

// 获得上传的文件名/images/girl/paojie.png
String fileName = uploadFileName.substring(uploadFileName.lastIndexOf("/") + 1);
// 获得文件的后缀名
String fileExtName = uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1);

/*
* 如果文件后缀名fileExtName不是我们所需要的 就直按return.不处理,告诉用户文件类型不对。
*/

System.out.println("文件信息[件名: " + fileName + " ---文件类型" + fileExtName + "]");
// 可以使用UID(唯一识别的通用码),保证文件名唯
// 0UID. randomUUID(),随机生一个唯一识别的通用码;
String uuidPath = UUID.randomUUID().toString();

// ================处理文件完毕==============

// 存到哪? uploadPath
// 文件真实存在的路径realPath
String realPath = uploadPath + "/" + uuidPath;
// 给每个文件创建一个对应的文件夹
File realPathFile = new File(realPath);
if (!realPathFile.exists()) {
realPathFile.mkdir();
}
// ==============存放地址完毕==============


// 获得文件上传的流
InputStream inputStream = fileItem.getInputStream();
// 创建一个文件输出流
// realPath =真实的文件夹;
// 差了一个文件;加上翰出文件的名产"/"+uuidFileName
FileOutputStream fos = new FileOutputStream(realPath + "/" + fileName);

// 创建一个缓冲区
byte[] buffer = new byte[1024 * 1024];
// 判断是否读取完毕
int len = 0;
// 如果大于0说明还存在数据;
while ((len = inputStream.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
// 关闭流
fos.close();
inputStream.close();

msg = "文件上传成功!";
fileItem.delete(); // 上传成功,清除临时文件
//=============文件传输完成=============
}
}
return msg;

}
}

info.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
   <title>Title</title>
</head>
<body>
${msg}
</body>
</html>

 注意:上传文件时出现500错误时,

 java.lang.ClassNotFoundException: org.apache.commons.fileupload.FileItemFactory

可能是因为本地tomcat中缺少上面的两个jar包,在tomcat lib中导入jar包即可;

 

 

posted @ 2020-08-07 15:42  小菜bxb  阅读(164)  评论(0编辑  收藏  举报