java web 一行代码实现文件上传下载

2024-09-04 06:08

本文主要是介绍java web 一行代码实现文件上传下载,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

       每当要实现文件上传下载的功能时,都要复制粘贴拼凑代码。如果用了不同的框架,代码还不一样,配置啥的一堆,甚是繁琐,不喜欢。科学家们喜欢把纷繁复杂的自然现象总结为一个个简洁的公式,我们也来试试,把上传下载整成一行代码~

       花了一天时间,整了个通用的工具类FileUtils,这个类里实际只包含两个静态方法,一个上传upload(),一个下载download()。只依赖apache的commons-fileupload.jar和commons-io.jar,不依赖struts和spring mvc等框架。干净简洁通用。上传下载文件只需一行代码即可搞定。现将代码贴上来,与大家共享,谁有好的想法,欢迎提议。

工具类:FileUtils.java

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;public class FileUtils {private FileUtils() {}public static void download(HttpServletRequest request,HttpServletResponse response, String relativeFilePath) {try {request.setCharacterEncoding("UTF-8");response.setCharacterEncoding("UTF-8");String fileName = request.getSession().getServletContext().getRealPath("/")+ relativeFilePath;fileName = fileName.replace("\\", "/");//统一分隔符格式File file = new File(fileName);//如果文件不存在if (file == null || !file.exists()) {String msg = "file not exists!";System.out.println(msg);PrintWriter out = response.getWriter();out.write(msg);out.flush();out.close();return;}String fileType = request.getSession().getServletContext().getMimeType(fileName);if (fileType == null) {fileType = "application/octet-stream";}response.setContentType(fileType);System.out.println("文件类型是:" + fileType);String simpleName = fileName.substring(fileName.lastIndexOf("/")+1);String newFileName = new String(simpleName.getBytes(), "ISO8859-1");response.setHeader("Content-disposition", "attachment;filename="+newFileName);BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());byte[] buffer = new byte[1024];int length = 0;while ((length = bis.read(buffer)) != -1) {bos.write(buffer, 0, length);}if (bis != null)bis.close();if (bos != null)bos.close();} catch (UnsupportedEncodingException e) {e.printStackTrace();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}/*** 文件上传* * @param request HttpServletRequest* @param relativeUploadPath 上传文件保存的相对路径,例如"upload/",注意,末尾的"/"不要丢了* @param maxSize 上传的最大文件尺寸,单位字节* @param thresholdSize 最大缓存,单位字节* @param fileTypes 文件类型,会根据上传文件的后缀名判断。<br>* 比如支持上传jpg,jpeg,gif,png图片,那么此处写成".jpg .jpeg .gif .png",<br>* 也可以写成".jpg/.jpeg/.gif/.png",类型之间的分隔符是什么都可以,甚至可以不要,<br>* 直接写成".jpg.jpeg.gif.png",但是类型前边的"."不能丢* @return*/public static List<String> upload(HttpServletRequest request, String relativeUploadPath, int maxSize, int thresholdSize, String fileTypes) {// 设置字符编码try {request.setCharacterEncoding("UTF-8");} catch (UnsupportedEncodingException e1) {e1.printStackTrace();}String tempPath = relativeUploadPath + "temp"; // 临时文件目录String serverPath = request.getSession().getServletContext().getRealPath("/").replace("\\", "/");fileTypes = fileTypes.toLowerCase(); // 将后缀全转换为小写//如果上传文件目录和临时目录不存在则自动创建if (!new File(serverPath + relativeUploadPath).isDirectory()) {new File(serverPath + relativeUploadPath).mkdirs();}if (!new File(serverPath + tempPath).isDirectory()) {new File(serverPath + tempPath).mkdirs();}DiskFileItemFactory factory = new DiskFileItemFactory();factory.setSizeThreshold(thresholdSize); // 最大缓存factory.setRepository(new File(serverPath + tempPath));// 临时文件目录ServletFileUpload upload = new ServletFileUpload(factory);upload.setSizeMax(maxSize);// 文件最大上限List<String> filePaths = new ArrayList<String>();List<FileItem> items;try {items = upload.parseRequest(request);// 获取所有文件列表for (FileItem item : items) {// 获得文件名,文件名包括路径if (!item.isFormField()) { // 如果是文件// 文件名String fileName = item.getName().replace("\\", "/");//文件后缀名String suffix = null;if (fileName.lastIndexOf(".") > -1) {suffix = fileName.substring(fileName.lastIndexOf("."));} else { //如果文件没有后缀名,不处理,直接跳过本次循环continue;}// 不包含路径的文件名String SimpleFileName = fileName;if (fileName.indexOf("/") > -1) {SimpleFileName = fileName.substring(fileName.lastIndexOf("/") + 1);}// 如果文件类型字符串中包含该后缀名,保存该文件if (fileTypes.indexOf(suffix.toLowerCase()) > -1) {String uuid = UUID.randomUUID().toString();SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");String absoluteFilePath = serverPath+ relativeUploadPath + sf.format(new Date())+ " " + uuid + " " + SimpleFileName;item.write(new File(absoluteFilePath));filePaths.add(absoluteFilePath);} }}} catch (FileUploadException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}return filePaths;}/*** 文件上传* * @param request HttpServletRequest* @param relativeUploadPath 上传文件保存的相对路径,例如"upload/",注意,末尾的"/"不要丢了* @param maxSize 上传的最大文件尺寸,单位字节* @param fileTypes 文件类型,会根据上传文件的后缀名判断。<br>* 比如支持上传jpg,jpeg,gif,png图片,那么此处写成".jpg .jpeg .gif .png",<br>* 也可以写成".jpg/.jpeg/.gif/.png",类型之间的分隔符是什么都可以,甚至可以不要,<br>* 直接写成".jpg.jpeg.gif.png",但是类型前边的"."不能丢* @return*/public static List<String> upload(HttpServletRequest request, String relativeUploadPath, int maxSize, String fileTypes) {return upload(request, relativeUploadPath, maxSize, 5*1024, fileTypes);}/*** 文件上传,不限大小* * @param request HttpServletRequest* @param relativeUploadPath 上传文件保存的相对路径,例如"upload/",注意,末尾的"/"不要丢了* @param fileTypes 文件类型,会根据上传文件的后缀名判断。<br>* 比如支持上传jpg,jpeg,gif,png图片,那么此处写成".jpg .jpeg .gif .png",<br>* 也可以写成".jpg/.jpeg/.gif/.png",类型之间的分隔符是什么都可以,甚至可以不要,<br>* 直接写成".jpg.jpeg.gif.png",但是类型前边的"."不能丢* @return*/public static List<String> upload(HttpServletRequest request, String relativeUploadPath, String fileTypes) {return upload(request, relativeUploadPath, -1, 5*1024, fileTypes);}
}
上传文件的方法又写了两个重载,用法一看便知,不再解释。

使用示例:FileUtilsTest.java

import java.io.IOException;
import java.util.List;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import common.utils.FileUtils;public class FileUtilsTest extends HttpServlet {private static final long serialVersionUID = 1L;public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {//下载文件FileUtils.download(request, response, "files/学生信息.xls");}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {//上传文件List<String> filePaths = FileUtils.upload(request, "upload/",".xls .xlsx");System.out.println(filePaths);}
}


不管是用struts还是spring mvc还是原生的servlet,拿到request,response都是轻而易举吧,然后上传下载就只需要上边的一行代码了^_^

测试一下:

看看后台打印结果:

上传成功,再来测测下载:

也没问题。

以后再需要上传下载功能的时候,只需要导入两个jar包,把FileUtils类复制过去,然后FileUtils.download(),FileUtils.upload()就可以啦^_^

项目下载地址:http://download.csdn.net/detail/u013314786/9252777

考虑到项目版本问题,压缩包中只包含了src和WebRoot两个文件夹,要运行项目,只需在eclipse或者myeclipse中新建一个名为FileUtils的项目,然后把src里的文件复制到项目的src文件夹下,WebRoot里的文件复制到项目的WebRoot(myeclipse默认)或者WebContent(eclipse默认)文件夹下就可以运行啦。


这篇关于java web 一行代码实现文件上传下载的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1135208

相关文章

Redis客户端连接机制的实现方案

《Redis客户端连接机制的实现方案》本文主要介绍了Redis客户端连接机制的实现方案,包括事件驱动模型、非阻塞I/O处理、连接池应用及配置优化,具有一定的参考价值,感兴趣的可以了解一下... 目录1. Redis连接模型概述2. 连接建立过程详解2.1 连php接初始化流程2.2 关键配置参数3. 最大连

SpringBoot多环境配置数据读取方式

《SpringBoot多环境配置数据读取方式》SpringBoot通过环境隔离机制,支持properties/yaml/yml多格式配置,结合@Value、Environment和@Configura... 目录一、多环境配置的核心思路二、3种配置文件格式详解2.1 properties格式(传统格式)1.

Apache Ignite 与 Spring Boot 集成详细指南

《ApacheIgnite与SpringBoot集成详细指南》ApacheIgnite官方指南详解如何通过SpringBootStarter扩展实现自动配置,支持厚/轻客户端模式,简化Ign... 目录 一、背景:为什么需要这个集成? 二、两种集成方式(对应两种客户端模型) 三、方式一:自动配置 Thick

Python实现网格交易策略的过程

《Python实现网格交易策略的过程》本文讲解Python网格交易策略,利用ccxt获取加密货币数据及backtrader回测,通过设定网格节点,低买高卖获利,适合震荡行情,下面跟我一起看看我们的第一... 网格交易是一种经典的量化交易策略,其核心思想是在价格上下预设多个“网格”,当价格触发特定网格时执行买

Spring WebClient从入门到精通

《SpringWebClient从入门到精通》本文详解SpringWebClient非阻塞响应式特性及优势,涵盖核心API、实战应用与性能优化,对比RestTemplate,为微服务通信提供高效解决... 目录一、WebClient 概述1.1 为什么选择 WebClient?1.2 WebClient 与

Java.lang.InterruptedException被中止异常的原因及解决方案

《Java.lang.InterruptedException被中止异常的原因及解决方案》Java.lang.InterruptedException是线程被中断时抛出的异常,用于协作停止执行,常见于... 目录报错问题报错原因解决方法Java.lang.InterruptedException 是 Jav

深入浅出SpringBoot WebSocket构建实时应用全面指南

《深入浅出SpringBootWebSocket构建实时应用全面指南》WebSocket是一种在单个TCP连接上进行全双工通信的协议,这篇文章主要为大家详细介绍了SpringBoot如何集成WebS... 目录前言为什么需要 WebSocketWebSocket 是什么Spring Boot 如何简化 We

java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)

《java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)》:本文主要介绍java中pdf模版填充表单踩坑的相关资料,OpenPDF、iText、PDFBox是三... 目录准备Pdf模版方法1:itextpdf7填充表单(1)加入依赖(2)代码(3)遇到的问题方法2:pd

Java Stream流之GroupBy的用法及应用场景

《JavaStream流之GroupBy的用法及应用场景》本教程将详细介绍如何在Java中使用Stream流的groupby方法,包括基本用法和一些常见的实际应用场景,感兴趣的朋友一起看看吧... 目录Java Stream流之GroupBy的用法1. 前言2. 基础概念什么是 GroupBy?Stream

python设置环境变量路径实现过程

《python设置环境变量路径实现过程》本文介绍设置Python路径的多种方法:临时设置(Windows用`set`,Linux/macOS用`export`)、永久设置(系统属性或shell配置文件... 目录设置python路径的方法临时设置环境变量(适用于当前会话)永久设置环境变量(Windows系统