图片上传及预览接口

上传及预览

@PostMapping("/uploadImg")
public ResponseResult uploadImage(@RequestParam("file") MultipartFile file) {
    return imageService.uploadImage(file);
}
public ResponseResult uploadImage(String original, MultipartFile file) {
        //判断是否有文件
        if (file == null) {
            return ResponseResult.FAILED("图片不可以为空.");
        }
        //判断文件类型,我们只支持图片上传,比如说:png,jpg,gif
        String contentType = file.getContentType();
        log.info("contentType == > " + contentType);
        if (TextUtils.isEmpty(contentType)) {
            return ResponseResult.FAILED("图片格式错误.");
        }
        //获取相关数据,比如说文件类型,文件名称
        String originalFilename = file.getOriginalFilename();
        String type = getType(contentType, originalFilename);
        if (type == null) {
            return ResponseResult.FAILED("不支持此图片类型");
        }
        //限制文件的大小
        long size = file.getSize();
 
        if (size > maxSize) {
            return ResponseResult.FAILED("图片最大仅支持" + (maxSize / 1024 / 1024) + "Mb");
        }
        //创建图片的保存目录
        //规则:配置目录/日期/类型/ID.类型
        long currentMillions = System.currentTimeMillis();
        String currentDay = new SimpleDateFormat("yyyy_MM_dd").format(currentMillions);
        log.info("current day == > " + currentDay);
        String dayPath = imagePath + File.separator + currentDay;
        File dayPathFile = new File(dayPath);
        //判断日期文件夹是否存在//2020_06_26
        if (!dayPathFile.exists()) {
            dayPathFile.mkdirs();
        }
        String targetName = String.valueOf(idWorker.nextId());
        String targetPath = dayPath +
                File.separator + type + File.separator + targetName + "." + type;
        File targetFile = new File(targetPath);
        //判断类型文件夹是否存在//gif
        if (!targetFile.getParentFile().exists()) {
            targetFile.getParentFile().mkdirs();
        }
        try {
            if (!targetFile.exists()) {
                targetFile.createNewFile();
            }
            log.info("targetFile == > " + targetFile);
            //保存文件
            file.transferTo(targetFile);
            Map<String, String> result = new HashMap<>();
            String resultPath = currentMillions + "_" + targetName + "." + type;
            result.put("id", resultPath);
            result.put("name", originalFilename);
            Image image = new Image();
            image.setContentType(contentType);
            image.setId(targetName);
            image.setCreateTime(new Date());
            image.setUpdateTime(new Date());
            image.setPath(targetFile.getPath());
            image.setName(originalFilename);
            image.setUrl(resultPath);
            image.setState("1");
            SobUser sobUser = userService.checkSobUser();
            image.setUserId(sobUser.getId());
            //记录文件
            //保存记录到数据里
            imageDao.save(image);
            //返回结果
            return ResponseResult.SUCCESS("文件上传成功").setData(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseResult.FAILED("图片上传失败,请稍后重试");
    }
@Override
    public void viewImage(HttpServletResponse response, String imageId) throws IOException {
        //配置的目录已知
        //根据尺寸来动态返回图片给前端
        //好处:减少带宽占用,传输速度快
        //缺点:消耗后台的CPU资源
        //推荐做法:上传上来的时候,把图片复制成三个尺寸:大,中,小
        //根据尺寸范围,返回结果即可
        //需要日期
        String[] paths = imageId.split("_");
        String dayValue = paths[0];
        String format;
        format = new SimpleDateFormat("yyyy_MM_dd").format(Long.parseLong(dayValue));
        log.info("viewImage  format == > " + format);
        //ID
        String name = paths[1];
        //需要类型
        String type = name.substring(name.length() - 3);
        //使用日期的时间戳_ID.类型
        String targetPath = imagePath + File.separator + format + File.separator +
                type +
                File.separator + name;
        log.info("get image target path === > " + targetPath);
        File file = new File(targetPath);
        OutputStream writer = null;
        FileInputStream fos = null;
        try {
            response.setContentType("image/png");
            writer = response.getOutputStream();
            //读取
            fos = new FileInputStream(file);
            byte[] buff = new byte[1024];
            int len;
            while ((len = fos.read(buff)) != -1) {
                writer.write(buff, 0, len);
            }
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                fos.close();
            }
            if (writer != null) {
                writer.close();
            }
        }
    }

Java修改图片大小尺寸的简单实现

参照:Java修改图片大小尺寸的简单实现

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在微信小程序中上传文件,你可以使用 `wx.chooseImage` 或 `wx.chooseFile` 方法来上传图片或其他文件。 1. `wx.chooseImage` 方法可以让用户选择图片并上传至服务器,代码示例: ```js wx.chooseImage({ count: 1, // 最多可以选择的图片张数,默认1张 sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有 sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有 success: function (res) { // 返回选定照片的本地文件路径列表,tempFilePaths可作为img标签的src属性显示图片 var tempFilePaths = res.tempFilePaths; wx.uploadFile({ url: '服务器地址', // 上传接口地址 filePath: tempFilePaths[0], // 上传文件路径 name: 'file', // 上传文件名称 success: function (res) { // 上传成功后的处理逻辑 } }) } }) ``` 2. `wx.chooseFile` 方法可以让用户选择文件并上传至服务器,代码示例: ```js wx.chooseFile({ success(res) { // 选择文件后的处理逻辑 wx.uploadFile({ url: '服务器地址', // 上传接口地址 filePath: res.tempFilePaths[0], // 上传文件路径 name: 'file', // 上传文件名称 success: function (res) { // 上传成功后的处理逻辑 } }) } }) ``` 要预览上传的图片或文件,可以使用 `wx.previewImage` 方法来预览图片,代码示例: ```js wx.previewImage({ current: '当前图片的url', // 当前显示图片的链接,不填则默认为urls的第一张 urls: ['图片1的url', '图片2的url'] // 需要预览的图片链接列表 }) ``` 对于其他类型的文件,可以使用 `wx.openDocument` 方法来打开预览,代码示例: ```js wx.openDocument({ filePath: '文件的本地路径', success: function (res) { // 打开文档成功的处理逻辑 } }) ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值