需求想要上传文件到服务器,内部使用访问也不多,但是上传接口没有,又不想额外配置一个文件服务器,通过查阅资料发现Nginx自带文件上传功能。
1. 检查当前nginx是否包含 dav 模块
bash
nginx -V 2>&1 | findstr "dav"
输入该命令,检查,如果有的话,就可以使用了。
2. 配置上传接口
bash
location /eventFileUpload {
# 设置上传文件大小限制为 100M
client_max_body_size 100M;
# 指定文件保存路径(注意使用正斜杠:我用的是windows服务器)
alias E:/xxx/xxx/xxx;
# 开启目录浏览,方便查看已上传的文件
autoindex on;
# 启用 WebDAV 功能
dav_methods PUT DELETE MKCOL COPY MOVE;
# 允许创建多级目录
create_full_put_path on;
}
3. 调用上传
java
public static void main(String[] args) {
try {
// File path to upload
String filePath = "D:\\1.txt";
File file = new File(filePath);
if (!file.exists()) {
System.out.println("File does not exist: " + filePath);
return;
}
// Upload URL 注意这里哦,eventFileUpload 为nginx 配置的访问url。后面为文件地址,要放进来的服务器的文件地址,要加到这里,因为body只传了文件流,没有指定上传到哪个路径,需要在这里指定哦
String uploadUrl = "http://xxx/xxx/xxx/eventFileUpload/222/1.txt";
// Create OkHttp client
OkHttpClient client = new OkHttpClient();
// Create request body with file content
okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(
file,
MediaType.parse("application/octet-stream")
);
// Build PUT request
Request request = new Request.Builder()
.url(uploadUrl)
.put(requestBody)
.build();
// Execute request
System.out.println("Uploading file: " + filePath);
System.out.println("To URL: " + uploadUrl);
try (Response response = client.newCall(request).execute()) {
if (response.isSuccessful()) {
System.out.println("Upload successful!");
System.out.println("Response code: " + response.code());
if (response.body() != null) {
System.out.println("Response body: " + response.body().string());
}
} else {
System.out.println("Upload failed!");
System.out.println("Response code: " + response.code());
System.out.println("Response message: " + response.message());
if (response.body() != null) {
System.out.println("Response body: " + response.body().string());
}
}
}
} catch (Exception e) {
System.err.println("Error during file upload: " + e.getMessage());
e.printStackTrace();
}
}