基于spring boot 实现文件的上传 、删除 、修改 、下载 、预览

package com.example.demo.controller;

import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.util.unit.DataSize;
import org.springframework.web.bind.annotation.;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.MultipartConfigElement;
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;

@RestController
@Component
public class FileController {

/**
 *
 * 单文件上传
 */
@PostMapping("upload")
public String upload(MultipartFile file,String paths) {
    try {
        if (file.isEmpty()) {
            return "文件为空";
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();

        System.out.println("上传的文件名为:" + fileName);
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));

        System.out.println("文件的后缀名为:" + suffixName);
        // 设置文件存储路径
        //  写入文件的名称
        String path = paths + fileName;
        File dest = new File(path);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            // 新建文件夹
            dest.getParentFile().mkdirs();
        }
        // 文件写入
        file.transferTo(dest);
        System.out.println(file);
        return "上传成功";
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "上传失败";
}


/**
 *
 *多文件上传
 */
@RequestMapping(value = "/uploadMore", method = RequestMethod.POST)
@ResponseBody
public String handleFileUpload(HttpServletRequest request) {
    List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
    MultipartFile file = null;
    BufferedOutputStream stream = null;
    for (int i = 0; i < files.size(); ++i) {
        file = files.get(i);
        String filePath = "D://Text//";
        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();
                stream = new BufferedOutputStream(new FileOutputStream(
                        //设置文件路径及名字
                        new File(filePath + file.getOriginalFilename())));
                // 写入
                stream.write(bytes);
                stream.close();
            } catch (Exception e) {
                stream = null;
                return "第 " + i + " 个文件上传失败 ==> "
                        + e.getMessage();
            }
        } else {
            return "第 " + i
                    + " 个文件上传失败因为文件为空";
        }
    }
    return "上传成功";
}


/**
 *
 * 文件下载相关代码
 */
@RequestMapping("/download")
public String downloadFile(HttpServletRequest request, HttpServletResponse response) {
    // 设置文件名,根据业务需要替换成要下载的文件名
    String fileName = "大树.png";
    if (fileName != null) {
        //设置文件路径
        String realPath = "D://Text//";
        File file = new File(realPath, fileName);
        if (file.exists()) {
            // 设置强制下载不打开
            response.setContentType("application/force-download");
            // 设置文件8088
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer);
                    i = bis.read(buffer);
                }
                System.out.println("success");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    return null;
}


/**
 * 文件改名
 */
@GetMapping("/updating")
public String upName(String path,String oldname,String newname) {
        if (path != null && oldname !=null && newname != null){

            String f = renameFile(path, oldname, newname);
            return f;
        }
        return "值不可为null";
}


public static String renameFile(String path,String oldname,String newname){
    //新的文件名和以前文件名不同时,才有必要进行重命名
    if(!oldname.equals(newname)){
        File oldfile=new File(path+"/"+oldname);
        File newfile=new File(path+"/"+newname);
        if(!oldfile.exists()) {
            //重命名文件不存在
            return "文件修改失败,"+oldname+"文佳不存在";
        }
        //若在该目录下已经有一个文件和新文件名相同,则不允许重命名
        if(newfile.exists()) {
            System.out.println(newname + "已经存在!");
        }else{
            oldfile.renameTo(newfile);
        }
    }else{

        return "新文件名和旧文件名相同...";
    }
    return newname+"修改成功";
}


/**
 * 文件删除
 */
@GetMapping("/delete")
public String requestparmText(String fileName, String path) {
    String file = path + fileName;
    System.out.println(file);

    boolean f = delete(file);
    if (f!= true) {
        return "删除失败";
    }
    return "删除成功";
}


private static boolean delete(String file) {

    File files = new File(file);
    if (!files.exists()) {
        System.out.println("删除文件失败:" + file + "不存在!");
        return false;
    } else {
        if (files.isFile()) {
            return deleteFile(file);
        } else {
            return deleteDirectory(file);
        }
    }
}


private static boolean deleteFile(String file) {

    File files = new File(file);
    // 如果文件路径所对应的文件存在,并且是一个文件,则直接删除
    if (files.exists() && files.isFile()) {
        if (files.delete()) {
            System.out.println("删除单个文件" + files + "成功!");
            return true;
        } else {
            System.out.println("删除单个文件" + files + "失败!");
            return false;
        }
    } else {
        System.out.println("删除单个文件失败:" + files + "不存在!");
        return false;
    }
}


private static boolean deleteDirectory(String file) {

    // 如果dir不以文件分隔符结尾,自动添加文件分隔符
    if (!file.endsWith(File.separator)) {
        file = file + File.separator;
        File dirFile = new File(file);
        // 如果dir对应的文件不存在,或者不是一个目录,则退出
        if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
            System.out.println("删除目录失败:" + file + "不存在!");
            return false;
        }
        boolean flag = true;
        // 删除文件夹中的所有文件包括子目录
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            // 删除子文件
            if (files[i].isFile()) {
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag) {
                    break;
                }
                // 删除子目录
            } else if (files[i].isDirectory()) {
                flag = deleteDirectory(files[i].getAbsolutePath());
                if (!flag) {
                    break;
                }
            }
            if (!flag) {
                System.out.println("删除目录失败!");
            }
            return false;
        }
        // 删除当前目录
        if (dirFile.delete()) {
            System.out.println("删除目录" + file + "成功!");
            return true;
        } else {
        }
    }
    return false;
}


/**
 * 文件预览
 */
@GetMapping("look")
public Map<String,String> look(String file)throws FileNotFoundException, IOException {
    if (file != null) {
        Map<String,String> map = readfile("D:/Text");
        try {
            readfile("D:/Text");

            // deletefile("D:/file"); 
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return map;
    }
    return null;
}


private static Map readfile(String filepath) throws FileNotFoundException, IOException {
    Map<String, String>map= new HashMap();
    try {
        File file = new File(filepath);
        if (!file.isDirectory()) {
            System.out.println("文件");
            System.out.println("path=" + file.getPath());
            System.out.println("name=" + file.getName());
            map.put(file.getPath(),file.getName());

        } else if (file.isDirectory()) {
            System.out.println("文件夹");
            String[] filelist = file.list();
            for (int i = 0; i < filelist.length; i++) {
                File readfile = new File(filepath + "\\" + filelist[i]);
                if (!readfile.isDirectory()) {
                    System.out.println("path=" + readfile.getPath());
                    System.out.println("name=" +" "+ readfile.getName());
                   map.put(readfile.getPath(),readfile.getName());
                } else if (readfile.isDirectory()) {
                    readfile(filepath + "\\" + filelist[i]);
                }
            }
        }
    } catch (FileNotFoundException e) {
        System.out.println("readfile()   Exception:" + e.getMessage());
    }
    return map;
}


@Configuration
public class MultipartConfig {
    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        // 置文件大小限制,超出此大小页面会抛出异常信息
        factory.setMaxFileSize(DataSize.parse("2MB")); //KB,MB
        // 设置总上传数据总大小
        factory.setMaxRequestSize(DataSize.parse("20MB"));
        // 设置文件临时文件夹路径
        // factory.setLocation("E://test//");
        // 如果文件大于这个值,将以文件的形式存储,如果小于这个值文件将存储在内存中,默认为0
        // factory.setMaxRequestSize(0);
        return factory.createMultipartConfig();
    }
}

}

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值