松鼠的博客

导航

java文件上传和下载的方式

java上传文件和下载文件有很多种,我只介绍两种:一是io流,二是springmvc,本人更喜欢用springmvc的方式,因为更加简单
一io流,需要导入comment.io,和comment.beabuty两个jar
以jsp+servert为例直接上代码:

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 java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

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

@MultipartConfig
public class FileServlet extends HttpServlet {

/**
*
*/
private static final long serialVersionUID = 1L;

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// 获取请求参数: 区分不同的操作类型
String method = request.getParameter("method");
if ("upload".equals(method)) {
// 上传
upload(request,response);
}

else if ("downList".equals(method)) {
// 进入下载列表
downList(request,response);
}

else if ("down".equals(method)) {
// 下载
down(request,response);
}
}


/**
* 1. 上传
*/
private void upload(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

HttpSession session=request.getSession();
List<String> list=(List<String>)session.getAttribute("files");
if(list==null){
//如果集合为空,就创建一个集合
list=new ArrayList<String>();
}

try {
//获取文件描述信息
String desc=request.getParameter("desc");
//获取上传的文件
Part part=request.getPart("file");
//获取请求的信息
String name=part.getHeader("content-disposition");
//System.out.println(name);//测试使用
//System.out.println(desc);//

//获取上传文件的目录
String root=request.getServletContext().getRealPath("/upload");
System.out.println("测试上传文件的路径:"+root);

//获取文件的后缀
String str=name.substring(name.lastIndexOf("."), name.length()-1);
System.out.println("测试获取文件的后缀:"+str);

//生成一个新的文件名,不重复,数据库存储的就是这个文件名,不重复的
String fname=UUID.randomUUID().toString()+str;
//将文件名保存到集合中
list.add(fname);
//将保存在集合中的文件名保存到域中
session.setAttribute("files", list);

String filename=root+"\\"+fname;
System.out.println("测试产生新的文件名:"+filename);

//上传文件到指定目录,不想上传文件就不调用这个
part.write(filename);

request.setAttribute("info", "上传文件成功");
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("info", "上传文件失败");
}
String mainPage = "upload.jsp";
request.setAttribute("mainPage", mainPage);
RequestDispatcher dispatcher = request.getRequestDispatcher("main.jsp");
dispatcher.forward(request, response);

}


/**
* 2. 进入下载列表
*/
private void downList(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// 实现思路:先获取upload目录下所有文件的文件名,再保存;跳转到down.jsp列表展示

//1. 初始化map集合Map<包含唯一标记的文件名, 简短文件名> ;
Map<String,String> fileNames = new HashMap<String,String>();

//2. 获取上传目录,及其下所有的文件的文件名
String bathPath = getServletContext().getRealPath("/upload");
// 目录
File file = new File(bathPath);
// 目录下,所有文件名
String list[] = file.list();
// 遍历,封装
if (list != null && list.length > 0){
for (int i=0; i<list.length; i++){
// 全名
String fileName = list[i];
// 短名
String shortName = fileName.substring(fileName.lastIndexOf("#")+1);
// 封装
fileNames.put(fileName, shortName);
}
}

// 3. 保存到request域
request.setAttribute("fileNames", fileNames);
// 4. 转发
String mainPage = "downlist.jsp";
request.setAttribute("mainPage", mainPage);
RequestDispatcher dispatcher = request.getRequestDispatcher("main.jsp");
dispatcher.forward(request, response);

}


/**
* 3. 处理下载
*/
private void down(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// 获取用户下载的文件名称(url地址后追加数据,get)
String fileName = request.getParameter("fileName");
fileName = new String(fileName.getBytes("ISO8859-1"),"UTF-8");

// 先获取上传目录路径
String basePath = getServletContext().getRealPath("/upload");
// 获取一个文件流
InputStream in = new FileInputStream(new File(basePath,fileName));

// 如果文件名是中文,需要进行url编码
fileName = URLEncoder.encode(fileName, "UTF-8");
// 设置下载的响应头
response.setHeader("content-disposition", "attachment;fileName=" + fileName);

// 获取response字节流
OutputStream out = response.getOutputStream();
byte[] b = new byte[1024];
int len = -1;
while ((len = in.read(b)) != -1){
out.write(b, 0, len);
}
// 关闭
out.close();
in.close();


}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}

}


原理不多说了,就是通过读取http请求中的信息流,在cope到本地实现的

二springmvc方式实现就更加简单了,也直接上代码:
import com.xiaomin.qq.enums.ResponseEnum;
import com.xiaomin.qq.vo.ResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.math.BigDecimal;

/**
* @Author 无名小卒
* @Date 2020/6/11 2:41
* @Version 1.0
*/

@Slf4j
public class FileUtil {
/**
* * 获取文件大小
* *
* * @param size
* * @return
*
*/
public static String getPrintSize(long bytes) {

BigDecimal filesize = new BigDecimal(bytes);
BigDecimal megabyte = new BigDecimal(1024 * 1024);

float returnValue = filesize.divide(megabyte, 2, BigDecimal.ROUND_UP).floatValue();
if (returnValue > 1) {
return (returnValue + "MB");
}
BigDecimal kilobyte = new BigDecimal(1024);
returnValue = filesize.divide(kilobyte, 2, BigDecimal.ROUND_UP).floatValue();
return (returnValue + "KB");
}

/*上传文件*/
public static ResponseVo<Object> uploadFile(MultipartFile file, String newfileName) {
if (file.isEmpty()) {
return ResponseVo.error(ResponseEnum.ERROR);
}
try {
/*旧文件名*/
String fileName = file.getOriginalFilename();
/*文件存储的位置*/
String filePath = "D://upload//";
// 获取文件的拓展名
String extension = "." + FilenameUtils.getExtension(fileName);
/*获取文件类型*/
String type = file.getContentType();
/*获取文件大小*/
long size = file.getSize();
/*新文件名*/

File dest = new File(filePath + newfileName);
/*上传文件*/
file.transferTo(dest);
} catch (IOException e) {
log.error(e.toString(), e);
}
return ResponseVo.success(ResponseEnum.REQUESTER_SUCCESS);

}

/*下载文件*/
public static ResponseEntity<Object> downloadFile(String fileName) {
String filePath = "D://upload//";
File file = new File(filePath + fileName);
InputStreamResource resource = null;
try {
resource = new InputStreamResource(new FileInputStream((file)));
} catch (FileNotFoundException e) {
log.error(e.toString(), e);
}
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", String.format("attachment;filename=\"%s\"", file.getName()));
headers.add("Cache-Control", "no-cache,no-store,must-revalidate");
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
ResponseEntity<Object> responseEntity = ResponseEntity.ok()
.headers(headers)
.contentLength(file.length())
.contentType(MediaType.parseMediaType("application/text"))
.body(resource);
return responseEntity;
}

/*删除文件*/
public static ResponseVo deleleFile(String fileName) {
//根据文件夹获取此文件夹的真实路径既是绝对路径
String realPath = "D://upload//";
//打印看一下绝对路径是否有误
System.out.println(realPath);
//根据文件的路径获取此文件
File file = new File(realPath + "/" + fileName);
//判断此文件是否为空
if (file != null) {
//文件不为空,执行删除
file.delete();
return ResponseVo.success(ResponseEnum.REQUESTER_SUCCESS);
} else {
//为空提示错误信息
return ResponseVo.error(ResponseEnum.ERROR);
}

}

}

 

参考文章:http://blog.ncmem.com/wordpress/2023/12/12/java%e6%96%87%e4%bb%b6%e4%b8%8a%e4%bc%a0%e5%92%8c%e4%b8%8b%e8%bd%bd%e7%9a%84%e6%96%b9%e5%bc%8f/

欢迎入群一起讨论

 

 

posted on 2023-12-12 17:02  Xproer-松鼠  阅读(343)  评论(0编辑  收藏  举报