我正在使用MvcUriComponentsBuilder.fromMethodName()来获取URL列表,并将其返回到前端。以下是示例输出,其中我以localhost的形式获取域:
[ http://localhost:8081/files/1800_tiger.jpg/slideshow,http://localhost:8081/files/1800_trees.jpg/slideshow ]
我希望MvcUriComponentsBuilder代替我的本地主机,返回我的系统IP地址。以下是我的代码实现:
@CrossOrigin
@RestController
public class ContentResource {
@RequestMapping("/getAllFiles")
public ResponseEntity<List<String>> getAllFiles(@RequestParam String panelName) {
List<String> fileNamesList = panelFileListMap.get(panelName);
if (fileNamesList != null) {
List<String> allFiles = fileNamesList.stream()
.map(fileName -> MvcUriComponentsBuilder
.fromMethodName(ContentResource.class, "getFile", fileName, panelName).build().toString())
.collect(Collectors.toList());
return ResponseEntity.ok().body(allFiles);
} else {
throw new RuntimeException("No images are uploaded in category = " + panelName);
}
}
@GetMapping("/files/{filename:.+}/{panelName}")
@ResponseBody
public ResponseEntity<Resource> getFile(@PathVariable("filename") String filename,
@PathVariable("panelName") String panelname) {
Resource file = storageService.loadFile(filename, panelname);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"")
.body(file);
}
}
答案 0 :(得分:0)
我自己找到了解决方案:更改了getAllFiles方法,如下所示:
InetAddress ip = null;
@RequestMapping("/getAllFiles")
public ResponseEntity<List<String>> getAllFiles(@RequestParam String panelName) {
try {
ip = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
List<String> fileNamesList = panelFileListMap.get(panelName);
if (fileNamesList != null) {
List<String> allFiles = fileNamesList.stream()
.map(fileName -> MvcUriComponentsBuilder
.fromMethodName(ContentResource.class, "getFile", fileName, panelName)
.host(ip.getHostAddress()).build().toString())
.collect(Collectors.toList());
return ResponseEntity.ok().body(allFiles);
} else {
throw new RuntimeException("No images are uploaded in category = " + panelName);
}
}