package com.utils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
public class FileUtil {
/**
* 上传工具类 上传就是对前端获取的请求进行解析,对其中的文件数据进行write操作
*/
public static Map<String,String> upload(HttpServletRequest req,String path){
//创建map集合存放信息
Map<String,String> map=new HashMap<>();
//设置字符集
String encode="utf-8";
DiskFileItemFactory factory=new DiskFileItemFactory();
FileUpload fileUpload=new FileUpload(factory);
try {
List<FileItem> fileItems = fileUpload.parseRequest(req);
for (FileItem fileItem : fileItems) {
if (fileItem.isFormField()){ //如果是普通表单数据
String fieldName = fileItem.getFieldName();
String value = fileItem.getString(encode); //从表单中获取对应的参数值与值
//存放信息
map.put(fieldName,value);
}else { //如果是文件
String oldName = fileItem.getName();
String newName=null; //如果文件为空,将其设置为空
if (oldName!=null && (!"".equals(oldName))){
//对文件名进行重新赋值
UUID uuid=UUID.randomUUID();
newName= uuid + oldName.substring(oldName.lastIndexOf("."));
//写出文件
fileItem.write(new File(path,newName));
}
//存放信息
map.put(fileItem.getFieldName(),newName);
}
}
} catch (FileUploadException e) {
throw new RuntimeException(e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
} catch (Exception e) {
throw new RuntimeException(e);
}
return map;
}
/**
* 下载工具类 下载就是从本地输入数据再响应输出(后期从服务器下载)
*/
public static void download(String path, HttpServletResponse resp){
//获取文件名
String fileName = path.substring(path.lastIndexOf("/")+1);
//让浏览器进行下载
resp.setHeader("Content-Disposition","attachment;fileName="+fileName);
//创建本地输入流与响应输出流
FileInputStream in= null;
ServletOutputStream out =null;
try {
in = new FileInputStream(path);
out = resp.getOutputStream();
//创建字节数组
byte[] bytes=new byte[1024];
int length;
while ((length=in.read(bytes))!=-1){
out.write(bytes,0,length);
}
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}finally {
try {
if (in!=null){
in.close();
}
if (out!=null){
out.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
应用场景:
上传
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("type/html;charset=utf-8");
//上传到服务器
String realPath = req.getServletContext().getRealPath("/img");
//new File(realPath).mkdirs();
System.out.println(realPath);
// Map<String, String> upload = FileUtil.upload(req, "d:/log");
Map<String, String> upload = FileUtil.upload(req, realPath);
for (String s : upload.keySet()) {
String value = upload.get(s);
System.out.println(s+" : "+value);
}
}
下载
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
//接收前端请求路径
String path = req.getParameter("path");
FileUtil.download(path,resp);
}
注意,别忘了导包