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服务器的文件夹查看是否有这个文件

上传成功!!!

相关推荐
土星云SaturnCloud10 分钟前
边缘计算 + AI 视频存管一体机:快递末端网点分拣提效与安全管控实战方案
服务器·人工智能·ai·边缘计算
CarIise16 分钟前
Spring Boot入门:从项目创建到请求响应实战
spring boot
wdfk_prog21 分钟前
Wi-Fi Direct教程 02:从 wpa_cli main() 到 P2P_FIND——用源码注释追踪 CLI 控制命令发送
运维·服务器·网络·网络协议·ubuntu·p2p·wifi-direct
DD云验证29 分钟前
DD云验证,免费网络验证系统
服务器·python·易语言·网络验证·卡密验证
货拉拉技术32 分钟前
构建稳定的 AI Agent:Harness 工程的核心机制与实践思考
人工智能·后端·数据分析
hsfxuebao44 分钟前
Harness工程
后端·架构
马剑威(威哥爱编程)1 小时前
【AI全栈后端12-02】Spring Boot 跑通第一个 AI 对话接口:HR 政策问答机器人实战
java·人工智能·spring boot·机器人
暗夜行者之光1 小时前
LangGraph 实战:构建“自我修正”的代码生成 Agent
后端
IT枫斗者枫哥1 小时前
AI返回合法JSON,字段就可信吗?给抽取结果补一道业务校验
java·人工智能·后端
IT枫斗者枫哥1 小时前
同一个requestId换了参数,为什么不能直接返回旧结果?
java·后端