- 网上找了很多资料,基本都是copy的。我的项目是前后端分离的,然后图片是存在本地的。
- 前端js的下载方法
//这里的name和url也可以自己传进来
function downLoadFile(file_url) {
var url = file_url;
var name = file_url.substring(file_url.lastIndexOf("/") + 1);
var download = async () => {
let responsePromise = await fetch(url);
let blob = await responsePromise.blob();
let objectURL = window.URL.createObjectURL(blob);
let a = document.createElement('a');
a.href = objectURL;
a.download = name;
a.click();
a.remove();
};
download().then(r => {
console.log(r);
});
}
- 如果出现跨域问题的话
1、单个控制器方法CORS注解
@RestController
@RequestMapping("/system/test")
public class TestController {
@CrossOrigin
@GetMapping("/{id}")
public AjaxResult getUser(@PathVariable Integer userId) {
// ...
}
@DeleteMapping("/{userId}")
public AjaxResult delete(@PathVariable Integer userId) {
// ...
}
}
2、整个控制器启用CORS注解
@CrossOrigin(origins = "http://ruoyi.vip", maxAge = 3600)
@RestController
@RequestMapping("/system/test")
public class TestController {
@GetMapping("/{id}")
public AjaxResult getUser(@PathVariable Integer userId) {
// ...
}
@DeleteMapping("/{userId}")
public AjaxResult delete(@PathVariable Integer userId) {
// ...
}
}
3、全局CORS配置(在ResourcesConfig重写addCorsMappings方法)
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 通用配置
*
* @author GideonYeung
*/
@Configuration
public class ResourcesConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry)
{
// 设置允许跨域的路径
//TODO 因为我的文件地址是这样的http://127.0.0.1/gidoen/upload/gideon.jpg,所有我写成了这样,或者写成/**也可以
registry.addMapping("/upload/**")
// 设置允许跨域请求的域名
.allowedOrigins("*")
// 是否允许证书
.allowCredentials(true)
// 设置允许的方法
.allowedMethods("GET", "POST", "DELETE", "PUT")
// 设置允许的header属性
.allowedHeaders("*")
// 跨域允许时间
.maxAge(3600);
}
}