java - createNewFile() 不起作用并且图像未存储

标签 java image spring-mvc

我正在尝试将图像保存在本地计算机中并将其信息保存在数据库中。但没有数据被插入到数据库中。文件正在创建,但没有内容(0 字节)。

我正在使用 hibernate 和 spring mvc REST API。我正在从 Angular 7 应用程序接收数据。该程序正在实时服务器上运行,但不在我的本地计算机上运行。

在本地服务器上我收到此错误和响应

POST http://localhost:8080/com_bmis_app_war_exploded/api/product/save/19 500 core.js:15724 ERROR TypeError: Cannot read property 'length' of undefined at AppService.push../src/app/app.service.ts.AppService.errorObjToMap (app.service.ts:56) at SafeSubscriber._error (edit-product.component.ts:240) at SafeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub (Subscriber.js:192)...........

这是响应错误: HTTP 状态 500 – 内部服务器错误

Root Cause

java.lang.UnsupportedOperationException
    java.base/sun.nio.fs.WindowsFileSystemProvider.readAttributes(WindowsFileSystemProvider.java:193)
    java.base/java.nio.file.Files.readAttributes(Files.java:1763)
    com.bmis.app.controller.ProductController.saveProduct(ProductController.java:329)
    com.bmis.app.controller.ProductController.addProduct(ProductController.java:443)......................

这是我的代码:

private ResponseEntity saveProduct(Integer id, @Valid @RequestBody Product product, MultipartFile[] images, BindingResult bindingResult, HttpServletRequest request) throws IOException {
    HashMap response = new HashMap();
    boolean success = false;
    List errors = new ArrayList();
    HttpStatus httpStatus = HttpStatus.BAD_REQUEST;
    String message = "";
    Map data = new HashMap();
    Slugify slg = new Slugify();
    String directory = "C:/Users/dellm4700/Documents/images";

    Set<ProductImage> productImages = new HashSet<>();
    for (MultipartFile multipartFile : images) {
        ProductImage productImage = new ProductImage();
        productImage.setSize(multipartFile.getSize());
        productImage.setExtension(multipartFile.getContentType());
        productImage.setActualImageName(new Date().getTime() + multipartFile.getOriginalFilename());
        productImage.setStandardImageName(multipartFile.getOriginalFilename());
        productImage.setNameAtFilestore(slg.slugify(productImage.getActualImageName()));
        productImage.setThumbnailImageName("thumb_"+ new Date().getTime() + multipartFile.getOriginalFilename());
        productImage.setProduct(product);
        productImages.add(productImage);
        File imageFile = new File(directory + "/" + productImage.getActualImageName());
        imageFile.setReadable(true, false);
        imageFile.createNewFile();
        Set<PosixFilePermission> perms = Files.readAttributes(imageFile.toPath(), PosixFileAttributes.class).permissions();
        try {
            multipartFile.transferTo(imageFile);
            perms.add(PosixFilePermission.OTHERS_READ);
            perms.add(PosixFilePermission.GROUP_READ);
            perms.add(PosixFilePermission.OTHERS_READ);
            Files.setPosixFilePermissions(imageFile.toPath(), perms);
        } catch (IOException e) {
            e.printStackTrace();
        }

        File thumbFile = new File(directory + "/" + productImage.getThumbnailImageName());
        thumbFile.setReadable(true, false);
        thumbFile.createNewFile();
        Set<PosixFilePermission> thumbperms = Files.readAttributes(thumbFile.toPath(), PosixFileAttributes.class).permissions();
        perms.add(PosixFilePermission.OTHERS_READ);
        perms.add(PosixFilePermission.GROUP_READ);
        perms.add(PosixFilePermission.OTHERS_READ);
        Files.setPosixFilePermissions(thumbFile.toPath(), perms);

        try {
            Thumbnails.of(directory + "/" + productImage.getActualImageName())
                    .size(200, 200).keepAspectRatio(false)
                    .toFile(thumbFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    productImages.addAll(product.getProductImages());
    product.setProductImages(productImages);

    for (CustomAttribute customAttribute : product.getCustomAttributes()) {
        customAttribute.setProduct(product);
    }

    Claims claims = (Claims) request.getAttribute("claims");

    User user = userService.findById((Integer) claims.get("id"));

    productValidator.validate(product, bindingResult);

    if (id != null) {
        Product sourceProduct = productService.findById(id);
    //  sourceProduct.getPrices().clear();

        if (!(StringUtility.compare(sourceProduct.getName(), product.getName())) && (productService.findByName(product.getName()) != null)) {
            bindingResult.rejectValue("name", null, "Product with same name already exists");
            message = "Fill the form properly";
        } else if (!(StringUtility.compare(sourceProduct.getBarcode(), product.getBarcode())) && (productService.findByBarCode(product.getBarcode()) != null)) {
            message = "Fill the form properly";
            bindingResult.rejectValue("barcode", null, "Product with same barcode already exists");
        }

    //     DaoUtility.copyNonNullProperties(product, sourceProduct);
    //     product = sourceProduct;
    } else {
        if (productService.findByName(product.getName()) != null) {
            message = "Fill the form properly";
            bindingResult.rejectValue("name", null, "Product with same name already exists");
        } else if (productService.findByBarCode(product.getBarcode()) != null) {
            message = "Fill the form properly";
            bindingResult.rejectValue("barcode", null, "Product with same barcode already exists");
        }

    }

    try {
        if (!bindingResult.hasErrors()) {


            for (Price price : product.getPrices()) {
                price.setProduct(product);
            }

            if (id == null) {
                productService.save(product);

            } else {
                productService.update(product);
            }

            data.put("products", product);
            success = true;
            message = "Product Successfully added";
            httpStatus = HttpStatus.OK;

        } else {
            for (FieldError error : bindingResult.getFieldErrors()) {
                message = "Fill the form properly";
                errors.add(new ErrorMessage(error.getField(), error.getDefaultMessage()));
            }
        }

    } catch (Exception e) {
        errors.add(new ErrorMessage("error", e.getMessage()));
    }

    response.put("success", success);
    response.put("errors", errors);
    response.put("message", message);
    response.put("data", data);
    return new ResponseEntity(response, httpStatus);
}

最佳答案

问题实际上出在 PosixFilePermission 类上,因为该类仅适用于基于 Linux 的操作系统。 当使用 readAttributes() 方法时,它会出错,因为 Linux 有自己的方法来获取文件属性,而 Windows 有自己的方法。

关于java - createNewFile() 不起作用并且图像未存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58078424/

相关文章:

java - Tomcat 可以使用 JWT token 吗

python - 我有一个 PNG 图像,想知道如何在 python 中有效地将其转换为 PBM

c# - 使图像适合 PictureBox

java.lang.AssertionError : Status expected:<200> but was:<400>

java - 空值的 Spring 格式化程序

java - JAVE (Java Audio Video Encoder) 库异常仅在 Linux (CentOS 7)

java - 在 while 循环 shell 中运行 Java

java - 如何在 java 中用 while 循环叠加数字模式?

html - 整个文本文章中的多个 float 图像

java - 测试 Spring @MVC 注解