I. Introduction
Cross-domain problems often occur when working on projects that separate front-end and back-end. As long as you access the external network, you will get such an error. In fact, there are many reasons. It may be the mismatch between post and get requests at the front-end and back-end, like I encountered that problem in the previous article. Today when I was writing the file upload requirement, this problem occurred again. This time the error was the same as when I requested the csdn avatar to be returned to the front end.
2. Solve problems
Of course, it is common to see this problem. It is due to cross-domain (CORS), so to solve this kind of problem, add @CrossOrigin annotation on the controller , similar to the following.
@Api(description = "阿里云文件管理")
@RestController
@CrossOrigin
@RequestMapping("admin/oss/file")
public class FileController {
@Resource
private FileService fileService;
@ApiOperation("文件上传")
@PostMapping("upload")
public R upload(@ApiParam(value="文件",required = true)@RequestParam MultipartFile file,
@ApiParam(value="模块",required = true)@RequestParam String module){
try {
InputStream inputStream=file.getInputStream();
String originalFilename=file.getOriginalFilename();
String url=fileService.upload(inputStream,module,originalFilename);
return R.ok().message("上传成功").data("url",url);
} catch (IOException e) {
System.err.println(e);
throw new WphException(ResultCodeEnum.FILE_UPLOAD_ERROR);
}
}
}
3. @CrossOrigin
We know that the previous approach was to add response header information such as Access-Control-Allow-Origin to the request header file, and @CrossOrigin essentially uses spring's interceptor to add response header information such as Access-Control-Allow-Origin to the response. So it can achieve cross-domain. Actually the content of SpringMVC
After adding it, there will be no error when uploading files. At first, I thought it was a problem with the front end, so I struggled for a long time! !