资源处理程序没有禁用缓存?

rta7y2nd  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(282)

我已经创建了一个springboot2和angular应用程序(书店应用程序-管理员可以添加新书或编辑现有书籍)。我想提供保存在 resources/static/images 路径。当我通过api调用添加一个新的图像时,它工作得很好,但是当我尝试用不同的图像替换图像时(当我尝试编辑图书时),当我通过文件资源管理器检查文件夹时,但是当我访问链接时,图像会被替换为新图像 http://localhost:8181/images/16.png 它显示了旧的图像。在eclipse中,如果我右键单击项目并单击refresh http://localhost:8181/images/16.png 显示正确的图像。
为了防止这个问题,我编写了下面的代码,以防止缓存 static/images ,但它不起作用。
--资源处理程序

@Configuration
public class WebConfig  implements WebMvcConfigurer{

      @Override public void addResourceHandlers(ResourceHandlerRegistry registry) {

      // Register resource handler for images
          System.out.println("indisde cache images");
      registry.addResourceHandler("/images/**").addResourceLocations("classpath:/static/images/").setCachePeriod(0);
      }

}

--Spring应用

@SpringBootApplication
public class BookStoreApplication implements CommandLineRunner {

    @Autowired
    UserService userService;

    public static void main(String[] args) {
        SpringApplication.run(BookStoreApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {   

          User user2=new User(); 
          user2.setUserName("admin");
          user2.setPassword(SecurityUtility.passwordEncoder().encode("admin"));
          user2.setEmail("admin@admin.com");
          user2.setEnabled(true);
          user2.setFirstName("adminFirstName"); 
          user2.setLastName("adminLastName");
          user2.setPhone("223456789");
          Role role2=new Role();
          role2.setRoleId((long) 2);
          role2.setRoleName("ROLE_ADMIN"); 
          UserRole userRole2=new UserRole(user2,role2);
          Set<UserRole> userRoles2=new HashSet<UserRole>();
          userRoles2.add(userRole2);
          userService.CreateUser(user2, userRoles2);

    }
}

--控制器

@RequestMapping(value = "/add/image", method = RequestMethod.POST)
public ResponseEntity uploadImage(@RequestParam(name = "id") Long id, HttpServletRequest request,
        HttpServletResponse response) throws IOException {

    try {

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Iterator<String> imageNames = multipartRequest.getFileNames();
        System.out.println(imageNames);
        MultipartFile imageMutipart = multipartRequest.getFile(imageNames.next());
        byte[] imageBytes = imageMutipart.getBytes();

        String imageNameNew = id + ".png";

        BufferedOutputStream bout = new BufferedOutputStream(
                new FileOutputStream(new File("src/main/resources/static/images/" + imageNameNew)));
        bout.write(imageBytes);
        bout.flush();
        bout.close();
        return new ResponseEntity("Upload success", HttpStatus.OK);
    } catch (Exception e) {

        return new ResponseEntity("Upload failed", HttpStatus.BAD_REQUEST);
    }

}

--Angular 服务

upload(bookId: number) {
    this.makeFileRequest("http://localhost:8181/book/add/image?id="+bookId, [], this.filesToUpload).then((result) => {
        console.log(result);
    }, (error) => {
        console.log(error);
    });
  }

  modifyImage(bookId: number){
    if(this.filesToUpload.length>0){
        this.makeFileRequest("http://localhost:8181/book/add/image?id="+bookId, [], this.filesToUpload).then((result) => {
            console.log(result);
        }, (error) => {
            console.log(error);
        });
    }
  }
r1zhe5dt

r1zhe5dt1#

我可以使用下面的资源处理程序解决这个问题

@Configuration
public class AdditionalResourceWebConfiguration implements WebMvcConfigurer {

  @Override
  public void addResourceHandlers(final ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/media/**").addResourceLocations("file:///" + System.getProperty("user.dir") + "/src/main/media/");
  }
}

相关问题