文件上传与下载

 
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hk.sky.bean.Admin;
import com.hk.sky.bean.ImgFile;
import com.hk.sky.common.Result;
import com.hk.sky.service.ImgFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/imgFile")
public class FileController {
    @Value("${saveImg.upload.path}")
    private String uploadPath;

    @Autowired
    ImgFileService imgFileService;
        
//文件上传
    @PostMapping("/upload")
    public Result upload(@RequestParam(value = "file") MultipartFile multipartFile) throws IOException {
        String originalFilename = multipartFile.getOriginalFilename();
        String type = FileUtil.extName(originalFilename);
        long size=multipartFile.getSize();

        //定义一个文件的唯一标识
        String uuid= IdUtil.fastSimpleUUID();
        String fileUUID=uuid+ StrUtil.DOT+type;
        //判断文件的放置路径是否存在
        File fileUpload = new File(uploadPath + fileUUID);
        File parentPath=fileUpload.getParentFile();
        if(!parentPath.exists()){
           parentPath.mkdirs();
        }
        String url;
        //把获取的文件存储到磁盘目录
        multipartFile.transferTo(fileUpload);

        url="http://localhost:8090/imgFile/"+fileUUID;

        return Result.Success(url);
    }

//文件下载
    @GetMapping("/{fileUUID}")
    public void download(@PathVariable String fileUUID, HttpServletResponse response) throws IOException {
        File uploadFile=new File(uploadPath+fileUUID);
        ServletOutputStream os=response.getOutputStream();
        response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileUUID,"UTF-8"));
        response.setContentType("application/octet-stream");

        os.write(FileUtil.readBytes(uploadFile));
        os.flush();
        os.close();
    }

                
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值