上传文件,下载文件操作

文件的上传和下载

1.创建数据表(id,路径)

CREATE TABLE `upload_files` (
  `uf_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '图片上传表id',
  `uf_save_path` varchar(255) DEFAULT NULL COMMENT '图片路径',
  PRIMARY KEY (`uf_id`)
) ENGINE=InnoDB AUTO_INCREMENT=83 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;

2.使用自动生成工具生成文件

3.新建pojo文件

package com.zt.secondfunction.pojo;

/**
 * @author zt
 * @date 2019/7/2 16:46
 */

public class LayuiCommonResponse {
    private Integer code;
    private String msg;
    private Integer count;
    private Object data;

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Integer getCount() {
        return count;
    }

    public void setCount(Integer count) {
        this.count = count;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }
}

新建enum文件

package com.zt.secondfunction.enums;

/**
 * @author zt
 * @date 2019/7/2 16:50
 */

public enum ZtCode {
    SUCCESS_UPLOAD(100001,"上传成功"),
    FAIL_UPLOAD(100002,"上传失败");

    private int code;
    private String info;

    ZtCode(int code, String info) {
        this.code = code;
        this.info = info;
    }

    public int getCode() {
        return code;
    }

    public String getInfo() {
        return info;
    }
}

 新建util文件

package com.zt.secondfunction.util;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;

public class Base64 {
    // 加密
    public static String getBase64(String str) {
        byte[] b = null;
        String s = null;
        try {
            b = str.getBytes("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (b != null) {
            s = new BASE64Encoder().encode(b);
        }
        return s;
    }

    // 解密
    public static String getFromBase64(String s) {
        byte[] b = null;
        String result = null;
        if (s != null) {
            BASE64Decoder decoder = new BASE64Decoder();
            try {
                b = decoder.decodeBuffer(s);
                result = new String(b, "utf-8");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * @param imgStr
     * @return
     * @Title: GenerateImage
     * @Description: TODO(base64字符串转化成图片)
     */
    public static String GenerateImage(String imgStr, String filePath) {
        if (imgStr == null) // 图像数据为空
            return "";
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] b = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 调整异常数据
                    b[i] += 256;
                }
            }
            // 生成jpeg图片


            String imgFilePath = filePath + getRandomFileName() + ".jpg";
            File dest = new File(imgFilePath);
            if (!dest.getParentFile().exists()) { //判断文件父目录是否存在
                dest.getParentFile().mkdir();
            }
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
            out.close();
            return imgFilePath;
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * @param imgPath
     * @return
     * @Title: GetImageStrFromPath
     * @Description: TODO(将一张本地图片转化成Base64字符串)
     */
    public static String GetImageStrFromPath(String imgPath) {
        InputStream in = null;
        byte[] data = null;
        // 读取图片字节数组
        try {
            in = new FileInputStream(imgPath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        // 返回Base64编码过的字节数组字符串
        return encoder.encode(data);
    }

    /**
     * 生成随机文件名:当前年月日时分秒+五位随机数
     *
     * @return
     */
    public static String getRandomFileName() {

        SimpleDateFormat simpleDateFormat;

        simpleDateFormat = new SimpleDateFormat("yyyyMMdd");

        Date date = new Date();

        String str = simpleDateFormat.format(date);

        Random random = new Random();

        int rannum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;// 获取5位随机数

        return rannum + str;// 当前时间
    }

    /**
     * 生成随机编号:当前年月日时分秒+六位随机数
     *
     * @return
     */
    public static String getAppUserNumber() {

        SimpleDateFormat simpleDateFormat;

        simpleDateFormat = new SimpleDateFormat("yyyyMMdd");

        Date date = new Date();

        String str = simpleDateFormat.format(date);

        Random random = new Random();

        int rannum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 100000;// 获取6位随机数

        return str + rannum;// 当前时间
    }

    /**
     * 获取当前时间戳
     * @return
     */
    public static String getCurrentTime() {

        SimpleDateFormat simpleDateFormat;

        simpleDateFormat = new SimpleDateFormat("yyyyMMdd");

        Date date = new Date();

        String str = simpleDateFormat.format(date);

        return str;// 当前时间
    }

    /**
     * 获取未来 第 past 天的日期
     * @param past
     * @return
     */
    public static String getFetureDate(int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + past);
        Date today = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String result = format.format(today);
        return result;
    }

    /**
     * 获取过去第几天的日期
     *
     * @param past
     * @return
     */
    public static String getPastDate(int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);
        Date today = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String result = format.format(today);
        return result;
    }

    /*
     * 将时间转换为时间戳
     */
    public static String dateToStamp(String s){
        try{
            String res;
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = simpleDateFormat.parse(s);
            long ts = date.getTime();
            res = String.valueOf(ts);
            return res;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}

4.新建controller文件

package com.zt.secondfunction.controller;

import com.zt.secondfunction.enums.ZtCode;
import com.zt.secondfunction.model.UploadFiles;
import com.zt.secondfunction.pojo.LayuiCommonResponse;
import com.zt.secondfunction.service.UploadFilesService;
import com.zt.secondfunction.util.Base64;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * @author zt
 * @date 2019/8/7 15:39
 */

@Api(value="file",description = "文件的上传下载",tags={"文件的上传下载"})
//@SpringBootApplication
@RestController
@RequestMapping("/file")
public class FileUploadController {

    @Autowired
    private UploadFilesService uploadFilesService;

    @ApiOperation(value = "上传文件", nickname = "/fileUpload", notes = "上传文件", tags={"@zt"})
    @RequestMapping(value = "/fileUpload",method = RequestMethod.POST,produces="application/json;charset=UTF-8")
    @ResponseBody
    public LayuiCommonResponse importFile(@RequestParam(value = "file", required = false) MultipartFile file){

        LayuiCommonResponse response = new LayuiCommonResponse();
        UploadFiles uploadFiles = new UploadFiles();
        try {
            String fileName = file.getOriginalFilename();

            String folderName = Base64.getRandomFileName();

            String os = System.getProperty("os.name");
            String ufSavePath = "";
            if (os.toLowerCase().startsWith("win")) {  //如果是Windows系统
                File dest = new File("D:/importFile/" + folderName + fileName);
                if (!dest.getParentFile().exists()) { //判断文件父目录是否存在
                    dest.getParentFile().mkdir();
                }
                try {
                    file.transferTo(dest); //保存文件
                    ufSavePath ="/importFile/" + folderName + fileName;

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else {  //linux 和mac
                File dest = new File("/usr/local/images/" + folderName + fileName);
                if (!dest.getParentFile().exists()) { //判断文件父目录是否存在
                    dest.getParentFile().mkdir();
                }
                try {
                    file.transferTo(dest); //保存文件
                    ufSavePath ="/images/" + folderName + fileName;

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            uploadFiles.setUfSavePath(ufSavePath);
            Integer ufId = uploadFilesService.insert(uploadFiles);
            uploadFiles.setUfId(ufId);
        } catch (Exception e) {
            e.printStackTrace();
            response.setCode(ZtCode.FAIL_UPLOAD.getCode());
            response.setMsg(ZtCode.FAIL_UPLOAD.getInfo());
            return response;
        }

        response.setCode(ZtCode.SUCCESS_UPLOAD.getCode());
        response.setMsg(ZtCode.SUCCESS_UPLOAD.getInfo());
        response.setData(uploadFiles);

        return response;
    }

 @ApiOperation(value = "下载文件", nickname = "/download", notes = "下载文件", tags = {"@张婷"})
    @ApiImplicitParam(name = "ufId", value = "文件id", required = true, paramType = "query", dataType = "int")
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    @ResponseBody
    public LayuiCommonResponse download(HttpServletResponse response, int ufId)
            throws IOException {
        LayuiCommonResponse response1 = new LayuiCommonResponse();
        FileInputStream is = null;
        BufferedInputStream bs = null;
        OutputStream os = null;
        try {
            UploadFiles uploadFiles = null;
            try {
                uploadFiles = uploadFilesService.selectUfSavePathById(ufId);
                String substring = uploadFiles.getUfSavePath().substring(uploadFiles.getUfSavePath().lastIndexOf("/") + 1);
                System.out.println(substring);
                String separator = File.separator;//用于区分window系统还是linux系统
                File csvFile = null;
                String str = "";
                if ("\\".equals(separator)){
                    //window下
                    str = "D:/importFile/" + uploadFiles.getUfSavePath().substring(uploadFiles.getUfSavePath().lastIndexOf("/")+1);
                    System.out.println("window路径--" + str);
                    str = str.replace("/","\\");
                    System.out.println("window路径--" + str);
                    csvFile = new File(str);
                }
                if ("/".equals(separator)){
                    //linux下
                    str = "/usr/local/csv/" + uploadFiles.getUfSavePath().substring(uploadFiles.getUfSavePath().lastIndexOf("/")+1);
                    System.out.println("linux路径--" + str);
                    str = str.replace("\\","/");
                    System.out.println("linux路径--" + str);
                    csvFile = new File(str);
                }
                File parent = csvFile.getParentFile();
                if (parent != null && !parent.exists()) {
                    parent.mkdirs();
                }
                csvFile.createNewFile();

                response.setHeader("Content-Disposition","application/octet-stream");
                response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("" + uploadFiles.getUfSavePath().substring(uploadFiles.getUfSavePath().lastIndexOf("/")+1), "UTF-8"));
                response.setCharacterEncoding("UTF-8");

                is = new FileInputStream(csvFile);
                bs =new BufferedInputStream(is);
                os = response.getOutputStream();
                byte[] buffer = new byte[1024];
                int len = 0;
                while((len = bs.read(buffer)) != -1){
                    os.write(buffer,0,len);
                }
            }finally {
                try{
                    if(is != null){
                        is.close();
                    }
                    if( bs != null ){
                        bs.close();
                    }
                    if( os != null){
                        os.flush();
                        os.close();
                    }
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
            response1.setCode(ZtCode.SUCCESS_GET.getCode());
            response1.setMsg(ZtCode.SUCCESS_GET.getInfo());
            response1.setData(uploadFiles);
        } catch (Exception e) {
            e.printStackTrace();
            response1.setCode(ZtCode.FAIL_GET.getCode());
            response1.setMsg(ZtCode.FAIL_GET.getInfo());
        }
        return response1;
    }

}

5.最后是service和实现类

package com.zt.secondfunction.service;

import com.zt.secondfunction.model.UploadFiles;
import org.springframework.stereotype.Service;

@Service
public interface UploadFilesService {

    /**
     * 上传图片
     * @param uploadFiles
     */
    Integer insert(UploadFiles uploadFiles);

    /**
     * 根据id查询路径
     * @param ufId
     * @return
     */
    UploadFiles selectUfSavePathById(int ufId);
}
package com.zt.secondfunction.service.impl;

import com.zt.secondfunction.mapper.UploadFilesMapper;
import com.zt.secondfunction.model.UploadFiles;
import com.zt.secondfunction.service.UploadFilesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author zt
 * @date 2019/8/7 15:52
 */

@Service
public class UploadFilesServiceImpl implements UploadFilesService {

    @Autowired
    private UploadFilesMapper uploadFilesMapper;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Integer insert(UploadFiles uploadFiles) {
        try {
            uploadFilesMapper.insert(uploadFiles);
            return uploadFiles.getUfId();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public UploadFiles selectUfSavePathById(int ufId) {
        try {
            return uploadFilesMapper.selectByPrimaryKey(ufId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值