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

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

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

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

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

2.新建controller写接口

@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服务器上运行,在服务器上运行,服务器其实就相当于项目的本地环境

还是刚才的项目

@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文件中添加

<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项目

依赖:

<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>
server:
  port: 8080

upload:
  path: http://你的文件服务器地址:9080/uploadFile
@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服务器的文件夹查看是否有这个文件

上传成功!!!

相关推荐

  1. golang文件ftp服务器

    2024-05-09 10:50:06       16 阅读
  2. 微信小程序 图片文件服务器

    2024-05-09 10:50:06       11 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-05-09 10:50:06       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-05-09 10:50:06       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-05-09 10:50:06       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-05-09 10:50:06       18 阅读

热门阅读

  1. python通过ssh远程打开windows的浏览器,不显示页面

    2024-05-09 10:50:06       13 阅读
  2. spark history server异常

    2024-05-09 10:50:06       13 阅读
  3. MQTT对比HTTP

    2024-05-09 10:50:06       11 阅读
  4. 中移物联网24届春招Offer笔面经

    2024-05-09 10:50:06       8 阅读
  5. 【c++实现获取web信息】

    2024-05-09 10:50:06       9 阅读
  6. 深度学习算法集成部署

    2024-05-09 10:50:06       9 阅读
  7. python基础 面向练习学习python1

    2024-05-09 10:50:06       10 阅读
  8. Django中如何使用WebSocket实时更新数据?

    2024-05-09 10:50:06       8 阅读
  9. 给定矢量初始位置,旋转角度,求解最终位置

    2024-05-09 10:50:06       15 阅读