SpringBoot上传文件到服务器(跨服务器上传)

目录

(一)上传文件到本地(windows)

(二)上传文件到linux服务器

(三)跨服务器上传文件


(一)上传文件到本地(windows)

1.新建一个文件夹来存储上传的文件

在application.yml中写上传的文件夹地址

我这里上传到F盘下的一个文件夹

2.新建controller写接口

java 复制代码
@RestController
public class UploadController {
    
    //获取yml中的文件上传地址
    @Value("${windows.path}")
    private String filePath;

    @PostMapping("/uploadFile")
    public Map<String, Object> uploadFile(@RequestParam("file") MultipartFile file){
        //返回map集合
        Map<String, Object> map = new HashMap<String, Object>();
        //判断文件名是否为空
        if (file.getOriginalFilename() == null){
            map.put("code",500);
            map.put("message","文件名为空!");
            return map;
        }
        try {
            //获取File文件
            File file1 = new File(filePath, file.getOriginalFilename());
            file.transferTo(file1);
        }catch (Exception e){
            map.put("code",500);
            map.put("message","文件服务器上传失败!");
            return map;
        }
        map.put("code",200);
        map.put("message","文件服务器上传成功!");
        return map;
    }
}

java.io.File类是文件和目录路径名称的抽象表示,主要用于文件和目录的创建、查找和删除等操作

我们新建一个File对象,使用里面的

public File(String parent,String child):从父路径字符串 和 子路径字符串创建新的File实例

这个对象会将父路径字符串与子路径字符串进行连接并转换为路径

然后调用file中的transferto() 方法即可完成上传

transferto() 方法的作用是将上传的文件保存到指定的目标位置

3.测试

发起请求

查看文件夹

上传本地成功!

(二)上传文件到linux服务器

这个其实也是上传到本地,因为我们的项目最终要放在linux服务器上运行,在服务器上运行,服务器其实就相当于项目的本地环境

还是刚才的项目

java 复制代码
@RestController
public class UploadController {

    @Value("${file.path}")
    private String filePath;

    @PostMapping("/uploadFile")
    public Map<String, Object> uploadFile(@RequestParam("file") MultipartFile file){
        Map<String, Object> map = new HashMap<String, Object>();
        if (file.getOriginalFilename() == null){
            map.put("code",500);
            map.put("message","文件名为空!");
            return map;
        }
        try {
            File file1 = new File(filePath, file.getOriginalFilename());
            //如果目标文件夹不存在就创建
            if (!file1.exists()){
                file1.createNewFile();
            }
            file.transferTo(file1);
        }catch (Exception e){
            map.put("code",500);
            map.put("message","文件服务器上传失败!");
            return map;
        }
        map.put("code",200);
        map.put("message","文件服务器上传成功!");
        return map;
    }
}

将项目打包部署到服务器上

在pom文件中添加

XML 复制代码
<build>
    <plugins>
    <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <version>2.6.7</version>
        <executions>
            <execution>
                <goals>
                    <goal>repackage</goal>
                </goals>
            </execution>
        </executions>
    </plugin>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <configuration>
            <skipTests>true</skipTests>
        </configuration>
    </plugin>
</plugins>
        </build>

打包后在项目的target文件夹下找到jar包

上传到服务器运行

运行成功后访问接口 服务器地址+端口+地址(本机访问必须开放服务器上的项目端口)

查看文件夹

上传成功!!!

(三)跨服务器上传文件

前面两个demo都是本地上传

这个是访问本地的项目去上传到远程服务器上,例如我有一个专门存储文件的服务器,我所有的项目都需要将文件存储到文件服务器上。当我们有多个服务器的时候就可以这样将所有服务的文件上传到我们规定的文件服务器中

例如:访问本地的项目(localhost)将文件上传到linux服务器上

将上个demo继续在服务器上运行,然后我们本地的服务去调用刚才那个部署在服务器上的项目的上传文件的接口

思路:访问一个服务器上的上传文件的接口,然后这个接口的方法再调用post请求去访问文件服务器上的上传文件的接口就行

继续新建一个demo项目

依赖:

XML 复制代码
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>2.0.21</version>
        </dependency>
XML 复制代码
server:
  port: 8080

upload:
  path: http://你的文件服务器地址:9080/uploadFile
java 复制代码
@RestController
public class UploadFileController {

    @Value("${upload.path}")
    private String uploadPath;

    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file) throws IOException {
        //文件为空
        if (file.isEmpty()){
            return "文件异常";
        }

        CloseableHttpClient client = HttpClients.createDefault();

        HttpPost httpPost = new HttpPost(uploadPath);

        HttpEntity httpEntity = MultipartEntityBuilder.create()
                .addBinaryBody("file", file.getBytes(), ContentType.MULTIPART_FORM_DATA, file.getOriginalFilename())
                .build();
        httpPost.setEntity(httpEntity);

        HttpResponse response = client.execute(httpPost);

        int statusCode = response.getStatusLine().getStatusCode();
        System.out.println(statusCode);
        return file.getOriginalFilename();
    }
}

调用http请求去访问文件服务器上的上传文件的接口

测试:

我们访问本地项目的上传文件接口

查看linux服务器的文件夹查看是否有这个文件

上传成功!!!

相关推荐
码luffyliu6 分钟前
系统优化:从压测到性能飞升
后端·压力测试
それども33 分钟前
Spring Bean 的name可以相同吗
java·后端·spring
上进小菜猪36 分钟前
基于深度学习的农业虫害自动识别系统:YOLOv8 的完整工程
后端
曹牧40 分钟前
C#:记录日志
服务器·前端·c#
运维行者_2 小时前
OPM 与传统管理工具的区别,在网络修复与自动化运维方面的优势在哪里?
运维·服务器·开发语言·网络·自动化·php·ssl
FAQEW2 小时前
若依(RuoYi-Vue)单体架构实战手册:自定义业务模块全流程开发指南
前端·后端·架构·若依二开
qq_12498707532 小时前
基于微信小程序的电子元器件商城(源码+论文+部署+安装)
java·spring boot·spring·微信小程序·小程序·毕业设计
a努力。2 小时前
美团Java面试被问:Redis集群模式的工作原理
java·redis·后端·面试
资生算法程序员_畅想家_剑魔3 小时前
Java常见技术分享-11-责任链模式
java·spring boot·责任链模式
计算机程序设计小李同学3 小时前
动漫之家系统设计与实现
java·spring boot·后端·web安全