keepalive_timeout 65;
#gzip on;
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
#访问路径拼接 upload 访问本地绝对路径下的某图片
location /upload/ {
alias D:/images/;
autoindex on;
}
location / {
root html;
index index.html index.htm;
}
#error_page 404 /404.html;
redirect server error pages to the static page /50x.htmlerror_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
#location ~ .php$ {
proxy_pass http://127.0.0.1;#}
pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000#location ~ .php$ {
root html; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param script_FILENAME /scripts$fastcgi_script_name; include fastcgi_params;#}
deny access to .htaccess files, if Apache’s document root concurs with nginx’s one#location ~ /.ht {
deny all;#}
}
#server {
listen 8000; listen somename:8080; server_name somename alias another.alias; location / { root html; index index.html index.htm; }#}
HTTPS server#server {
listen 443 ssl; server_name localhost; ssl_certificate cert.pem; ssl_certificate_key cert.key; ssl_session_cache shared:SSL:1m; ssl_session_timeout 5m; ssl_ciphers HIGH:!aNULL:!MD5; ssl_prefer_server_ciphers on; location / { root html; index index.html index.htm; }#}
}
配置好nginx.conf记得重启一下服务器。效果如图:
八、java后台代码
@RestController
public class FileController {
@PostMapping(value = “/fileUpload”)
public String fileUpload(@RequestParam(value = “file”) MultipartFile file) {
if (file.isEmpty()) {
System.out.println(“请选择图片”);
}
String fileName = file.getOriginalFilename(); // 文件名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
【一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义】 浏览器打开:qq.cn.hn/FTf 免费领取
// 后缀名
String filePath = “D:/images/”; // 上传后的路径
fileName = UUID.randomUUID() + suffixName; // 新文件名
File dest = new File(filePath + fileName);
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
} catch (IOException e) {
e.printStackTrace();
}
//返回图片名称
return fileName;
}
}
这里将图片上传至D:/images文件夹中,因为前面配置了nginx的缘故,我这里是在本地测试的,直接使用localhost/upload/+返回的图片名称就可以访问到了。
如果想要通过项目的地址外加端口号进行访问的话,可以配置一个资源映射路径。
@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/upload/**").addResourceLocations(“file:D:/images/”);
}
}
like this!
ry) {
registry.addResourceHandler("/upload/**").addResourceLocations(“file:D:/images/”);
}
}
like this!
[外链图片转存中…(img-2iXr2GkH-1636437365162)]



