java接口保存文件到本地指定目录下

该博客介绍了如何使用Java后端实现一个接口,将通过POST请求上传的文件保存到本地指定目录。后端代码中定义了一个`fileUpload`方法,接收MultipartFile参数,将文件写入到D:uploadDir路径下。通过Postman模拟页面上传,验证了接口功能的正确性,文件成功保存到本地。
摘要由CSDN通过智能技术生成

java接口保存文件到本地指定目录下.md

一、需求

通过接口将 file 保存到本地指定目录下

动动发财小手,关注 + 点赞 + 收藏不迷路。

二、后端代码

package com.web.controller;


import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;

/**
 * @Author: tinker
 * @Date: 2022/02/18 10:25
 */
@Slf4j
@RestController
public class FileUploadController {

    @PostMapping("/file/upload")
    String fileUpload(@RequestParam("file") MultipartFile file) {
        String path = "D:\\uploadDir\\";
        // 获取文件名(包括后缀)
        String fileName = file.getOriginalFilename();
        try (FileOutputStream fos = new FileOutputStream(path + fileName)) {
            fos.write(file.getBytes());
            return "文件上传成功";
        } catch (Exception e) {
            log.error("file upload failed, fileName = {}", file.getOriginalFilename(), e);
        }
        return "文件上传失败";
    }

}

三、postman模拟页面上传

step1:
POST 请求,url = localhost:8080/file/upload

step2:
点击Body,选择 form-data,key 为 file,之后点击 value 选择一个文件,文件名为 test.txt

step3:
点击上传,可以发现本地 uploadDir 目录下已经上传成功了

  • 2
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值