Long Tian Xiao Shi12: 00: 06
Upload files to server or local
Controller layer: Note (the return value is encapsulated by myself, you can change it according to your needs)
//上传文件到文件服务器并且指定到位置
@RequestMapping(value = "/uploads",method = {RequestMethod.POST,RequestMethod.GET})
//Java后台设置全局跨域
@CrossOrigin(origins = "*", allowCredentials = "true",allowedHeaders = "",methods = {})
public RestResult uploadFile(@RequestParam("file")MultipartFile file) throws IOException {
if(file !=null){
return complaintService.upload(file);
}
return new RestResultBuilder().error("文件不存在!");
}
Service layer code:
public RestResult upload(MultipartFile file) throws IOException {
//获取文件名
String fileName = file.getOriginalFilename();
System.out.println("文件名为"+fileName);
//获取文件的后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
System.out.println("后缀名为"+suffixName);
//解决中文问题,linux下中文路径,图片显示问题
fileName = UUID.randomUUID().toString().replace("-", "") + suffixName;
//返回客户端文件路径图片显示问题
String url = "http://ip:port/项目名"+"/upload/"+fileName;
//String url = "localhost:8090"+"/upload/" + fileName;
System.out.println("服务器返回的路径"+url);
File dest = new File(ApiConstant.UPLOAD_PATH + fileName);
System.out.println("目录为"+dest);
// 检测是否存在目录
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
file.transferTo(dest);
return new RestResultBuilder().setCode(0).setMsg("长传成功").setData(url).build();
}
Tools
public class ApiConstant {
// Header 中 token 的 key
public final static String AUTHORIZATION = "***********";
// JWTUtil Redis 数据库 用户 key 前缀
public static String USER_JWT_PREFIX = "********";
// Header 中 sign 的 key
public static final String HEADER_ENCRYPTE_SIGN = "***********";
// 该项目签名 sign-key
public static final String SIGN_KEY = "******************";
//上面没有可以不配置
/**
* 文件上传路径填自己路径
*/
public static final String UPLOAD_PATH = "/home/file/";
/**
* 放在Tomcat的同一目录路径下
*/
public static final String PRO_UPLOAD_PATH = "/home/ggj/soft/upload/";
//本地路径
public static final String DEV_UPLOAD_PATH = "D:/upload/";
Configuration class
@Configuration
public class uploadConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/upload/**").addResourceLocations("file:/home/file/");
//registry.addResourceHandler("/upload/**").addResourceLocations("file:D:/upload/");
}
So far: the file upload is no problem! First test whether the local can upload, and then package the upload server to try whether the server can upload!