springboot实现文件上传到liunx服务器
springboot实现文件上传到liunx服务器上保存
1.首先配置服务器环境,这时候我们要在服务器上安装tomcat服务器通过tomcat来进行
2.安装好tomcat服务后,对tomcat进行配置:
1)找到tomcat文件所在位置打开conf文件夹下的server.xml 加上一个context标签,表示/img路径可以访问到/home/img下的文件
2)修改conf文件夹下的web.xml文件,如果没有设置readonly为false会报错409
注意:服务器要放行tomcat的端口号
到此,服务器端配置就基本做好!
接下来是代码实现:
1)首先导入跨域上传依赖(使用jersey)
<!-- 跨域上传依赖--> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-core</artifactId> <version>1.18.1</version> </dependency> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-client</artifactId> <version>1.18.1</version> </dependency>
2)对yml文件进行配置,设置上传文件最大值
spring: servlet: multipart: enabled: true max-file-size: 30MB max-request-size: 30MB
3)代码实现
@PostMapping("/upLoadImg") @ResponseBody public String doRemoteUpload(MultipartFile myfile){ String path = "http://{ip地址(如:127.0.0.1)}:8080/img/"; //为上传到服务器的文件取名,使用UUID防止文件名重复 String type= myfile.getOriginalFilename().substring(myfile.getOriginalFilename().lastIndexOf(".")); String filename= UUID.randomUUID().toString()+type; try{ //使用Jersey客户端上传文件 Client client = Client.create(); WebResource webResource = client.resource(path +"/" + URLEncoder.encode(filename,"utf-8")); webResource.put(myfile.getBytes()); System.out.println("上传成功"); System.out.println("图片路径==》"+path+filename); }catch(Exception ex){ System.out.println("上传失败"); } return "任意"; }