文件上传和下载的工具类
下面展示 上传的代码
。
public static void upload(MultipartFile file, String name){
//获取文件的后缀 这个获取是会携带.的 注意
String suffixName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
//设置文件上传的地址 这里做演示 所以我写死了的
//如果你们要上传的文件夹经常变 可以写在配置文件里
String fileUrl = "F:/image"+"/"+name+suffixName;
//判断该文件夹是否存在 不存在的话就创建
//这个地方容易报错无操作权限,这个时候百度去查怎么开放权限就可以了,这里不做详情解答
File dest = new File(fileUrl);
if(!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
//保存文件
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(fileUrl));
outputStream.write(file.getBytes());
outputStream.flush();
outputStream.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
下面展示一些 下载的代码
。
public static void download(String path, HttpServletResponse res){
InputStream fis=null;
OutputStream toClient=null;
try {
//获取下载的路径
File file=new File(path);
//获取文件名
String filename=file.getName();
//取得文件的后缀名
String ext=filename.substring(filename.lastIndexOf(".")+1).toUpperCase();
//以流的形式下载文件
fis=new BufferedInputStream(new FileInputStream(file));
System.out.println("文件大小:"+fis.available());
//创建一个和文件一样大小的缓存区
byte[] buffer=new byte[fis.available()];
//读取流
fis.read(buffer);
//清空首部空白行
res.reset();
//设置文件下载后的指定文件名
res.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes("gb2312"),"ISO8859-1"));
res.addHeader("Content-Length", "" + file.length());
//response.getOutputStream() 获得字节流,通过该字节流的write(byte[] bytes)可以向response缓冲区中写入字节,再由Tomcat服务器将字节内容组成Http响应返回给浏览器。
toClient = new BufferedOutputStream(res.getOutputStream());
res.setContentType("application/octet-stream");
//将buffer 个字节从指定的 byte 数组写入此输出流。
toClient.write(buffer);
//刷新此缓冲的输出流。这迫使所有缓冲的输出字节被写出到底层输出流中。 把缓存区的数据全部写出
toClient.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
//关闭流
fis.close();
//关闭缓冲输出流
toClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
头一次写文章,不太会写什么花里胡哨的,这个是我之前写的工具类,可以通用,理解起来也比较轻松。正常接口 直接调用即可,上传的方法 可以自己改返回值,因为大部分公司用的话 肯定是要保存地址到数据库的