文件上传通用类,主要是前后的分类

1,文件上传server,代码

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by sean on 2018/5/2.
 */
@Service
public class UploadFileBiz {
 
    //这个路径是配置在application.yml
    @Value("${uploadPath}")
    private String uploadPath;
    @Autowired
    private FileEntityBiz fileEntityBiz;

    public ResultBean fileUpload(FileVo fileVo) throws Exception {
        String filename = "";
        String filePath = "";
        MultipartFile file = fileVo.getFiles()[0];
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(new Date());
            String[] split = format.split("-");
            String dateDir = "";
            for (String str : split) {
                dateDir += str + "/";
            }
            String path = uploadPath + dateDir;
            File dir = new File(path);

            //上传的位置,如果不存在创建一个文件夹
            if (!dir.exists()) {
                dir.mkdirs();
            }
            //上传文件名
            String oldName = file.getOriginalFilename();
            if (oldName.contains("[") || oldName.contains("]")) {
                oldName = oldName.replaceAll("]", "");
                oldName = oldName.replaceAll("\\[", "");
            }
            //获取新的名字 只按照当前时间毫秒获取。。可加UUID
            File serverFile = new File(path + oldName);
            if (serverFile.exists()) {
                int count = 1;
                boolean flag = true;
                while (flag) {
                    filename = oldName.replaceAll(oldName.substring(oldName.lastIndexOf(".")), "") + "(" + count + ")" + oldName.substring(oldName.lastIndexOf("."));
                    serverFile = new File(path + oldName.replaceAll(oldName.substring(oldName.lastIndexOf(".")), "") + "(" + count + ")" + oldName.substring(oldName.lastIndexOf(".")));
                    if (!serverFile.exists()) {
                        System.out.println("不存在");
                        flag = false;
                    }
                    count++;
                }
            } else {
                filename = oldName;
            }
            //在保存图片位置创建文件
            //把内存图片写入磁盘中
            file.transferTo(serverFile);
            filePath = dateDir + filename;
        } catch (IOException e) {
            return new ResultBean(e);
        }
        //持久化到数据库,记录数相对路径
        FileEntity fileEntity = new FileEntity();
        fileEntity.setEntityId(fileVo.getEntityId());
        fileEntity.setFileName(filename);
        fileEntity.setEntityType(fileVo.getEntityType());
        fileEntity.setFilePath(filePath);
        fileEntity.setFileSize(file.getSize());
        fileEntity.setFileContentType(file.getContentType());
        fileEntityBiz.insert(fileEntity);
        return ResultBean.ok();
    }

    public void downloadFile(HttpServletResponse res, String fileName) throws UnsupportedEncodingException {
        File file = new File(uploadPath + fileName);
        if (!file.exists()) {
            return;
        }
        res.reset(); // 非常重要
        res.setHeader("Access-Control-Allow-Origin", res.getHeader("Origin"));
        res.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
        res.setHeader("Access-Control-Max-Age", "3600");
        res.setHeader("Access-Control-Allow-Headers", "content-type,Device,Authorization,Origin,Platform,Cookie,remember-me");
        res.setHeader("Access-Control-Allow-Credentials", "true");
        res.setHeader("content-type", "application/octet-stream");
        res.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        res.setContentType("application/octet-stream");
        res.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = res.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(new File(uploadPath
                    + fileName)));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public ResultBean fileUploadForBase64(String base64Data, HttpServletRequest request) {
        String filename = "";
        try {
            String dataPrix = "";
            String data = "";
            if (base64Data == null || "".equals(base64Data)) {
                return new ResultBean(new Exception("上传失败,上传图片数据为空"));
            } else {
                String[] d = base64Data.split("base64,");
                if (d != null && d.length == 2) {
                    dataPrix = d[0];
                    data = d[1];
                } else {
                    return new ResultBean(new Exception("上传失败,数据不合法"));
                }
            }
            String suffix = "";
            if ("data:image/jpeg;".equalsIgnoreCase(dataPrix)) {
                //data:image/jpeg;base64,base64编码的jpeg图片数据
                suffix = ".jpg";
            } else if ("data:image/x-icon;".equalsIgnoreCase(dataPrix)) {
                //data:image/x-icon;base64,base64编码的icon图片数据
                suffix = ".ico";
            } else if ("data:image/gif;".equalsIgnoreCase(dataPrix)) {
                //data:image/gif;base64,base64编码的gif图片数据
                suffix = ".gif";
            } else if ("data:image/png;".equalsIgnoreCase(dataPrix)) {
                //data:image/png;base64,base64编码的png图片数据
                suffix = ".png";
            } else {
                return new ResultBean(new Exception("上传图片格式不合法"));
            }
            String tempFileName = System.currentTimeMillis() + suffix;

            //因为BASE64Decoder的jar问题,此处使用spring框架提供的工具包
            byte[] bs = Base64Utils.decodeFromString(data);
            try {
                //使用apache提供的工具类操作流

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String format = sdf.format(new Date());
                String dateDir = "";
                String[] split = format.split("-");
                for (String str : split) {
                    dateDir += str + "/";
                }
                String path = uploadPath + dateDir;
                File dir = new File(path);
                //上传的位置,如果不存在创建一个文件夹
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                FileUtils.writeByteArrayToFile(new File(path + tempFileName), bs);
                filename = dateDir + tempFileName;
            } catch (Exception ee) {
                return new ResultBean(new Exception("上传失败,写入文件失败," + ee.getMessage()));
            }
        } catch (Exception e) {
            return new ResultBean(e);
        }
        return new ResultBean(filename);
    }

    public ResultBean deleteFile(Integer id) {
        FileEntity fileEntity = fileEntityBiz.selectById(id);
        if (fileEntity != null) {
            File file = new File(uploadPath + fileEntity.getFilePath());
            if (file.exists()) {
                file.delete();
             int falg= fileEntityBiz.deleteByIdFlag(id);
             if(falg>0){
                 return ResultBean.build("删除成功");
             }
            }
        }
        return ResultBean.build("文件不存在");
    }

    public int deleteFile(FileEntity fileEntity) {
            File file = new File(uploadPath + fileEntity.getFilePath());
            if (file.exists()) {
                file.delete();
                int flag = fileEntityBiz.deleteByIdFlag(fileEntity.getId());
                if (flag > 0) {
                    return flag;
                }
            }
        return -1;
    }

    //提交多个文件
    public ResultBean fileUploads(FileVo fileVo) throws Exception {
        String filename = "";
        String filePath = "";
        List<Map<String, String>> list;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(new Date());
            String[] split = format.split("-");
            String dateDir = "";
            for (String str : split) {
                dateDir += str + "/";
            }
            System.out.println();
            String path = uploadPath + dateDir;
            File dir = new File(path);

            //上传的位置,如果不存在创建一个文件夹
            if (!dir.exists()) {
                dir.mkdirs();
            }
            //上传文件名
            list = new ArrayList<>();
            for (MultipartFile file : fileVo.getFiles()) {
                String oldName = file.getOriginalFilename();
                if (oldName.contains("[") || oldName.contains("]")) {
                    oldName = oldName.replaceAll("\\[", "");
                    oldName = oldName.replaceAll("]", "");
                }
                //获取新的名字 只按照当前时间毫秒获取。。可加UUID
                File serverFile = new File(path + oldName);
                if (serverFile.exists()) {
                    int count = 1;
                    boolean flag = true;
                    while (flag) {
                        filename = oldName.replaceAll(oldName.substring(oldName.lastIndexOf(".")), "") + "(" + count + ")" + oldName.substring(oldName.lastIndexOf("."));
                        serverFile = new File(path + oldName.replaceAll(oldName.substring(oldName.lastIndexOf(".")), "") + "(" + count + ")" + oldName.substring(oldName.lastIndexOf(".")));
                        if (!serverFile.exists()) {
                            flag = false;
                        }
                        count++;
                    }
                } else {
                    filename = oldName;
                }
                //在保存图片位置创建文件
                //把内存图片写入磁盘中
                file.transferTo(serverFile);
                filePath = dateDir + filename;
                FileEntity fileEntity = new FileEntity();
                fileEntity.setEntityId(fileVo.getEntityId());
                fileEntity.setFileName(filename);
                fileEntity.setEntityType(fileVo.getEntityType());
                fileEntity.setFilePath(filePath);
                fileEntity.setFileSize(file.getSize());
                fileEntityBiz.insert(fileEntity);
            }
        } catch (IOException e) {
            return ResultBean.build(e.getMessage());
        }

        return ResultBean.ok(list);
    }


}

  2,工具文件工具类

public class FileVo {
    private MultipartFile[] files;
    private Integer entityId;
    private String entityType;

    public MultipartFile[] getFiles() {
        return files;
    }

    public void setFiles(MultipartFile[] files) {
        this.files = files;
    }

    public Integer getEntityId() {
        return entityId;
    }

    public void setEntityId(Integer entityId) {
        this.entityId = entityId;
    }

    public String getEntityType() {
        return entityType;
    }

    public void setEntityType(String entityType) {
        this.entityType = entityType;
    }
}

 

 


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值