一个sprinboot中的文件上传和下载的接口类

一个sprinboot中的文件上传和下载的接口类

        • 1、接口
        • 2、FileUploadUtil 类

1、接口

前端通过调用/image和/video方法即可获得媒体数据,
而其中url参数的传递则是通过upload返回的url来获取。

    @Resource
    FileUploadUtil fileUploadUtil;

    @Resource
    HttpServletResponse httpServletResponse;
	//上传文件接口
    @PostMapping("/upload")
    public String test(MultipartFile file) {
        String url = fileUploadUtil.upload(file);
        return url;
    }
	//下载图片接口
    @GetMapping(value = "/image", produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public byte[] getImage(@RequestParam("url") String url) throws IOException {
        File file = new File(fileUploadUtil.getPictureUrl() + url);
        FileInputStream inputStream = new FileInputStream(file);
        byte[] bytes = new byte[inputStream.available()];
        inputStream.read(bytes, 0, inputStream.available());
        return bytes;
    }
	//下载视频接口
    @GetMapping(value = "/video")
    @ResponseBody
    public byte[] getVideos( @RequestParam("url") String url) throws IOException {
        File file = new File(fileUploadUtil.getPictureUrl() + url);
        httpServletResponse.setHeader("Content-Type", "video/MP4");
        FileInputStream inputStream = new FileInputStream(file);
        byte[] bytes = new byte[inputStream.available()];
        inputStream.read(bytes, 0, inputStream.available());
        return bytes;
    }

2、FileUploadUtil 类

将文件上传到根路径下/src/main/resources/static/位置中。


import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;
@Component
public class FileUploadUtil {

    FileUploadUtil (){
        String bootPath = System.getProperty("user.dir");
        bootPath = bootPath.replace("\\","/");
        this.pictureUrl = bootPath+"/src/main/resources/static/";

    }

    private String pictureUrl;

    public String getPictureUrl() {
        return pictureUrl;
    }

    public void setPictureUrl(String pictureUrl) {
        this.pictureUrl = pictureUrl;
    }

    public String upload(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        File saveFile = new File(pictureUrl);
        if (!saveFile.exists()) {
            //若不存在该目录,则创建目录
            saveFile.mkdir();
        }
        //拼接url,采用随机数,保证每个图片的url不同
        UUID uuid = UUID.randomUUID();
        //拼接后的url
        String url = uuid+fileName.substring(fileName.lastIndexOf("."));

        try {
            //将文件保存指定目录
            file.transferTo(new File(pictureUrl + url));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return url;
    }
}

你可能感兴趣的:(java,servlet,前端)