文件上传
在开发过程汇中,避免不了和文件打交道,这时,就需要学习文件上传相关技术,有的公司购买了第三方oss服务,直接调用第三方SDK即可
但有的公司不想花费这笔费用,就只能搭建nginx图片服务了,而且nginx图片服务也挺不错的,自己可以买个轻量服务器,把一些喜欢的图片、音乐、视频等放在服务器的,也很方便的去浏览
一、文件上传到第三方服务平台
这种方式,都是需要调用第三方相关平台:
- 阿里云OSS
- 腾讯云
- 华为云
- 七牛云
- 其他......
每个平台都是大同小异,我对接过阿里云的OSS,之后有时间会补充相关代码
二、文件上传到服务器指定目录,并进行外网访问
1.Linux系统
1.在linux系统上创建存放文件的目录:mkdir usr/local/images
2.安装nginx,并配置图片服务器相关配置
有两种情况:
1.linux直接安装的nginx:
配置如下:
user root;
worker_processes 2;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 8092;
server_name 192.168.31.185;
resolver 8.8.8.8 valid=60s;
resolver_timeout 3s;
location /images/ {
root /usr/local/;
autoindex on;
}
location / {
root html;
index index.html index.htm;
}
}
}
2.linux使用宝塔安装的nginx:
配置如下:
user www www;
worker_processes auto;
error_log /www/wwwlogs/nginx_error.log crit;
pid /www/server/nginx/logs/nginx.pid;
worker_rlimit_nofile 51200;
stream {
log_format tcp_format '$time_local|$remote_addr|$protocol|$status|$bytes_sent|$bytes_received|$session_time|$upstream_addr|$upstream_bytes_sent|$upstream_bytes_received|$upstream_connect_time';
access_log /www/wwwlogs/tcp-access.log tcp_format;
error_log /www/wwwlogs/tcp-error.log;
include /www/server/panel/vhost/nginx/tcp/*.conf;
}
events
{
use epoll;
worker_connections 51200;
multi_accept on;
}
http
{
include mime.types;
#include luawaf.conf;
include proxy.conf;
default_type application/octet-stream;
server_names_hash_bucket_size 512;
client_header_buffer_size 32k;
large_client_header_buffers 4 32k;
client_max_body_size 50m;
sendfile on;
tcp_nopush on;
keepalive_timeout 60;
tcp_nodelay on;
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
fastcgi_buffer_size 64k;
fastcgi_buffers 4 64k;
fastcgi_busy_buffers_size 128k;
fastcgi_temp_file_write_size 256k;
fastcgi_intercept_errors on;
gzip on;
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_http_version 1.1;
gzip_comp_level 2;
gzip_types text/plain application/javascript application/x-javascript text/javascript text/css application/xml;
gzip_vary on;
gzip_proxied expired no-cache no-store private auth;
gzip_disable "MSIE [1-6]\.";
limit_conn_zone $binary_remote_addr zone=perip:10m;
limit_conn_zone $server_name zone=perserver:10m;
server_tokens off;
access_log off;
server
{
listen 8005;
server_name 39.101.136.70;
# index index.html index.htm index.php;
# root /www/wwwroot/default/herwen/hw_shuili/dist;
#error_page 404 /404.html;
include enable-php.conf;
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|mp4|pptx|pdf|mp3)$
{
expires 30d;
root /usr/local/images/; #存放图片的路径
proxy_store on;
proxy_temp_path /usr/local/images/; #存放图片的路径
proxy_redirect off;
proxy_set_header Host 39.101.136.70; #服务器IP地址
client_max_body_size 10m;
client_body_buffer_size 1280k;
proxy_connect_timeout 900;
proxy_send_timeout 900;
proxy_read_timeout 900;
proxy_buffer_size 40k;
proxy_buffers 40 320k;
proxy_busy_buffers_size 640k;
proxy_temp_file_write_size 640k;
if ( !-e $request_filename)
{
proxy_pass http://39.101.136:8005; #默认80,可修改
}
}
location ~ .*\.(js|css)?$
{
expires 12h;
}
location ~ /\.
{
deny all;
}
access_log /www/wwwlogs/access.log;
}
include /www/server/panel/vhost/nginx/*.conf;
}
3.具体代码实现:
3.1.在项目的application-dev.yml
配置如下:
#文件上传到服务器指定目录配置
fileUploadSetting:
#文件存放路径:
FOLDER_PATH: /usr/local/images
#服务器ip地址(公网)/域名:
HOST_ADDRESS: 192.168.31.125 #这里替换成自己服务器的ip
#文件访问路径(本地开发,可以使用IIS搭建图片服务器、部署到linux服务器时,可以使用nginx搭建图片服务器):
FILE_ADDRESS: :8005/
3.2.文件上传代码:
1.FileController
package com.water.modules.file;
import com.water.common.utils.UploadFileToServerUtils;
import com.water.config.baseConfig.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
/**
* @Classname test
* @Description:
* @Date: 2023/5/5 0005 10:29
* @AUTHOR: 无泪之城
* @Version 1.0
*/
@Api(tags = "文件管理")
@RestController
@RequestMapping("file")
public class FileController {
private UploadFileToServerUtils uploadFileToServerUtils;
@Autowired
public void setUploadFileToServerUtils(UploadFileToServerUtils uploadFileToServerUtils) {
this.uploadFileToServerUtils = uploadFileToServerUtils;
}
@ApiOperation("上传文件")
@PostMapping("/uploadFile")
public Result uploadFile(@RequestParam("file") @ApiParam(value = "二进制文件流") MultipartFile file) throws IOException {
return uploadFileToServerUtils.uploadFile(file);
}
@ApiOperation("删除文件")
@PostMapping("/deleteFile")
public Boolean uploadCustomPathFile(@RequestParam("path")String path){
return uploadFileToServerUtils.deleteFile(path);
}
}
2. UploadFileToServerUtils
package com.water.common.utils;
import com.water.config.baseConfig.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.FileSystemUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
/**
* @Classname UploadFileToServerUtils
* @Description:文件上传到服务器指定目录工具类
* @Date: 2023/5/5 0005 10:43
* @AUTHOR: 无泪之城
* @Version 1.0
*/
@Component
@Slf4j
public class UploadFileToServerUtils {
//文件存放路径
@Value("${fileUploadSetting.FOLDER_PATH}")
private String FOLDER_PATH;
//服务器ip地址
@Value("${fileUploadSetting.HOST_ADDRESS}")
private String HOST_ADDRESS;
@Value("${fileUploadSetting.FILE_ADDRESS}")
private String FILE_ADDRESS;
/**
* 上传文件
* @param file
* @return
*/
public Result uploadFile(MultipartFile file){
String fileName = file.getOriginalFilename();//获取文件名
if (!file.isEmpty()) {
try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(FOLDER_PATH + File.separator + fileName))) {
out.write(file.getBytes());
out.flush();
try {
//文件访问路径
String fileAddress=HOST_ADDRESS+FILE_ADDRESS+fileName;
log.info("文件上传成功,文件名:" + fileName+" url:"+fileAddress);
return new Result().ok(fileAddress);
} catch (Exception e) {
e.printStackTrace();
}
return new Result().error();
} catch (FileNotFoundException e) {
log.error("上传文件失败 FileNotFoundException:" + e.getMessage());
return new Result().error("上传文件失败 FileNotFoundException:"+e.getMessage());
} catch (IOException e) {
log.error("上传文件失败 IOException:" + e.getMessage());
return new Result().error("上传文件失败 IOException:" + e.getMessage());
}
} else {
log.error("上传文件失败,文件为空");
return new Result().error("上传文件失败,文件为空");
}
}
/**
* 删除指定文件夹或文件
* @param path
* @return
*/
public Boolean deleteFile(String path){
return FileSystemUtils.deleteRecursively(new File(path));
}
}
2.windows系统
2.1 在windows系统上,可以搭建iis服务来当做图片服务器:具体教程--直接百度即可
2.2 相关配置和上面一样,只不过可能存放路径等不同
本文来自博客园,作者:青喺半掩眉砂,转载请注明原文链接:https://www.cnblogs.com/xiaoguo-java/p/17541555.html