package utils;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class FileUtils {
private static String PATH = PropertiesUtil.readProperties("UP_DOWN_PATH");
public static List<String> uploadFile(HttpServletRequest request){
List<String> list = new ArrayList<>();
try {
Collection<Part> parts = request.getParts();
for (Part p: parts ) {
String fileName = p.getSubmittedFileName();
if(fileName !=null && fileName.length() > 0 ){
list.add(fileName);
p.write(PATH+fileName);
}
}
}catch (Exception e){
e.printStackTrace();
}
return list ;
}
public static void downloadFile(String fileName , HttpServletResponse resp){
ServletOutputStream outputStream = null;
try {
File file = new File(PATH+fileName);
resp.setContentType("application/octet-stream");
String newName = new String(fileName.getBytes("utf-8"), "iso-8859-1");
resp.setHeader("Content-Disposition","attachment;filename="+newName);
resp.addHeader("Content-Length", file.length() + "");
FileInputStream fis = new FileInputStream(file);
byte [] bs = new byte[1024*1024] ;
int i = -1 ;
outputStream = resp.getOutputStream();
while ((i = fis.read(bs)) != -1){
outputStream.write(bs);
outputStream.flush();
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
if(outputStream!=null){
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
文件上传下载FileUtils
最新推荐文章于 2024-08-19 16:01:20 发布