SpringBoot之文件上传到服务器

SpringBoot之文件上传到服务器

最近在做一个文件上传的功能,也是比较简单,这里算是记录一下吧

后台

其实我们最好能区分只是单纯的上传图片还是其他文件,这里记录一个可以传各种格式文件的和一个特定图片格式的

1.所有格式的文件:
/**
     * 文件上传
     *
     * @param
     * @return
     * @throws Exception
     */
    @PostMapping(path = "/fileUpload")
    @ResponseBody
    public Map<String, Object> fileUpload(@RequestParam("uploadfile") MultipartFile file, HttpServletRequest request) throws Exception {
        Map<String, Object> data = new HashMap<String, Object>();
        //这里是拿到文件名
        String fileName = file.getOriginalFilename();
        String sysTime = DateUtil.getCurrentTime24();
        //配置文件配置的上传地址--服务器地址
        String targetDir = propertiesDIY.getUpfilePath();
        //这里是工具类
        FileUtil.uploadFile(file.getBytes(), targetDir, fileName);
        data.put("fileurl", propertiesDIY.getUpfileUrl() + File.separator + sysTime.substring(0, 8) + File.separator + fileName);
        logger.info(" file ==>" + fileName + "==>upload to " + targetDir + "success");
        return ResponseUtil.toJson(PltResult.RESULT_0000, data);
    }

工具类:

public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
        File targetFile = new File(filePath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        //如果文件存在就先删除了
        File ifFile = new File(filePath + File.separator + fileName);
        if (ifFile.exists()) {
            logger.debug("File is exists!");
            ifFile.delete();
        }
        //然后再写文件
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(filePath + File.separator + fileName);
            out.write(file);
        } catch (Exception e) {
            logger.error("Error:", e);
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

Postman测试:
在这里插入图片描述
服务器看到的:
在这里插入图片描述

2.图片格式的文件:

这个思路就是前端先把图片用base64读取压缩成字符串,然后再把字符串写入成图片

    //image就是base64的字符串格式
    byte[] imageByte = Base64Helper.decode(image);
    File file = new File(filepath + filename);
    RandomAccessFile randomAccessFile = null;
    try{
        randomAccessFile=new RandomAccessFile(file,"rw");
        randomAccessFile.seek(0);
        try{
            randomAccessFile.write(imageByte);
        }catch(UnsupportedEncodingException e){
            logger.error("Error:",e);
        }
    }catch(IOException e){
        logger.error("Error:",e);
        throw e;
    }finally{
        if(randomAccessFile!=null){
            try{
                randomAccessFile.close();
            }catch(IOException e){
                logger.error("Error:",e);
            }
        }
    }
  • 1
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值