package com.example.ok.controller.File;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
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.File;
@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {
@Value("${file.upload.url}")
private String uploadFilePath;
@RequestMapping("/upload")
public String httpUpload(@RequestParam("files") MultipartFile files[]) throws JSONException {
JSONObject object=new JSONObject();
for(int i=0;i<files.length;i++){
String fileName = files[i].getOriginalFilename();
File dest = new File(uploadFilePath +'/'+ fileName);
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
files[i].transferTo(dest);
} catch (Exception e) {
log.error("{}",e);
object.put("success",2);
object.put("result","程序错误,请重新上传");
return object.toString();
}
}
object.put("success",1);
object.put("result","文件上传成功");
return object.toString();
}
}
在application.yml或application.properties中配置文件上传到的目录
#文件上传目录
file.upload.url=路径
记住要有传递的前端html页面:否则报错
<!--multipart/form-data 不对字符编码。当使用有文件上传控件的表单时,该值是必需的。-->
<!--multiple可接受多个值的文件上传字段:-->
<form action="/file/upload" method="post" enctype="multipart/form-data">
<input type="file" name="files" multiple="multiple" />
<button type="submit">上传</button>
</form>

可以实现了 参考自:https://cloud.tencent.com/developer/article/1594124

posted on   不爱美女爱辣条  阅读(10)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?



点击右上角即可分享
微信分享提示