Java_实现图片上传到服务器

首先,以富文本形式实现上传图片(●ˇ∀ˇ●) 不多赘述😂


    @ApiOperation(value="/image", notes = "上传图片")
    @RequestMapping(value = "/image", method = RequestMethod.POST)
    public RespBean uploadImage(HttpServletRequest request, MultipartFile image) throws IOException {
    
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        
        String filePath = "/images/" + sdf.format(new Date());
        String imageFolderPath = request.getServletContext().getRealPath(filePath);
        File imageFolder = new File(imageFolderPath);
        if (!imageFolder.exists()) {
            imageFolder.mkdirs();
        }

        StringBuilder imageUrl= new StringBuilder();
        imageUrl.append(request.getScheme())
                .append("://")
                .append(request.getServerName())
                .append(":")
                .append(request.getServerPort())
                .append(request.getContextPath())
                .append(filePath);

        String imageName = UUID.randomUUID() + "_" + image.getOriginalFilename().replaceAll(" ", "");
        try {
            IOUtils.write(image.getBytes(), new FileOutputStream(new File(imageFolder, imageName)));
            imageUrl.append("/").append(imageName);
            return new RespBean("success", imageUrl.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new RespBean("error", "上传失败!");
     }

再一个是上传缩略图,这个地方涉及到上传图片的压缩问题!🆗

@RestController
@RequestMapping("/upload")
public class ThumbnailController {

    @ApiOperation(value = "/minorimg", notes = "上传缩略图片")
    @RequestMapping(value = "/minorimg", method = RequestMethod.POST)
    public RespBean uploadImg(HttpServletRequest request, MultipartFile image) throws IOException {
    
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        
        String filePath = "/thumbnailimg/" + sdf.format(new Date());
        String imgFolderPath = request.getServletContext().getRealPath(filePath);
        File imgFolder = new File(imgFolderPath);
        if (!imgFolder.exists()) {
            imgFolder.mkdirs();
        }

        StringBuilder thumImgUrl = new StringBuilder();
        thumImgUrl.append(request.getScheme())
                .append("://")
                .append(request.getServerName())
                .append(":")
                .append(request.getServerPort())
                .append(request.getContextPath())
                .append(filePath);

        String imgName = UUID.randomUUID().toString() + ".jpg"; 
        
        try {
            byte[] ysbytes;
            try {
                ysbytes = compressImage(image.getInputStream(), 400);
            } catch (Exception e) {
                e.printStackTrace();
                log.error(image.getOriginalFilename() + "图片压缩失败...",e);
                imgName += "_" + image.getOriginalFilename().replaceAll(" ", "");
                ysbytes = image.getBytes();
            }

            IOUtils.write(ysbytes, new FileOutputStream(new File(imgFolder, imgName)));

            thumImgUrl.append("/").append(imgName);
            log.info("上传缩略图片:"+thumImgUrl.toString());
            return new RespBean("success", thumImgUrl.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new RespBean("error", "上传失败!");
    }

    /**
     * 图片压缩
     * @param fileStream
     * @param ppi
     * @return
     */
    public static byte[] compressImage(InputStream fileStream, int ppi) throws Exception {
        byte[] smallImage = null;

        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            Thumbnails.of(fileStream).size(ppi, ppi).outputFormat("jpg").toOutputStream(out);
            smallImage = out.toByteArray();
            return smallImage;
        } catch (Exception e) {
            throw new Exception("图片压缩失败...");
        }
    }
}

评论

暂无评论