springboot使用MultipartFile上传文件以及File与MultipartFile互转

    如下所示的代码,是一个在springboot项目中使用MultipartFile进行文件上传的示例:

package com.springboot.web;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/test")
public class UploadController {

    private String path = "d:/temp";

    @PostMapping("/upload")
    public ResponseEntity upload(MultipartFile file) {
        Map<String,Object> res = new HashMap<>();
        try {
            File outFile = new File(path.concat(File.separator).concat(file.getOriginalFilename()));
            file.transferTo(outFile);
            res.put("url",outFile.getAbsolutePath());
            res.put("code",200);
        } catch (Exception e) {
            e.printStackTrace();
            res.put("msg","upload fail");
            res.put("code",500);
        }
        return ResponseEntity.ok(res);
    }
}

    我们在前端页面上,进行配置上传的时候,可以使用这样的form:

  <form action="/test/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file"/>
    <input type="submit" value="upload"/&g
### 解决 Spring Boot 中 `MultipartFile` 文件上传为空的问题 当遇到 `MultipartFile` 上传文件为空的情况时,可能的原因有多个方面。以下是详细的解决方案: #### 配置 multipart 支持 为了支持多部分请求(multipart requests),需要确保应用程序已经正确配置了 multipart resolver。如果未指定特定的 multipart resolver,则可以考虑在 `application.properties` 或者 `application.yml` 中设置默认参数[^1]。 对于基于 XML 的配置方式,在 DispatcherServlet 上下文中定义 `<bean id="multipartResolver">...</bean>` 是一种常见做法;而在纯 JavaConfig 方式下则可以通过实现 WebMvcConfigurer 接口并重写 addResourceHandlers 方法来完成相同功能。 ```yaml spring.servlet.multipart.enabled=true spring.servlet.multipart.max-file-size=10MB spring.servlet.multipart.max-request-size=10MB ``` #### 检查前端表单提交 确认 HTML 表单是否设置了正确的编码类型 (`enctype`) 属性值为 `"multipart/form-data"`,这一步骤非常重要因为只有这样才能让浏览器发送二进制数据给服务器端处理程序接收[^2]。 ```html <form action="/upload" method="post" enctype="multipart/form-data"> Select file to upload: <input type="file" name="file"/> <button>Submit</button> </form> ``` #### 控制器方法签名验证 确保控制器中的处理器方法能够接收到传入的文件对象,并且该对象被声明为 `@RequestParam("file") MultipartFile file` 形式的参数。注意这里的 "file" 应匹配于客户端表单字段名称[^3]。 ```java @PostMapping("/upload") public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file){ if(file.isEmpty()){ return new ResponseEntity<>("Please select a file!", HttpStatus.BAD_REQUEST); } try { byte[] bytes = file.getBytes(); Path path = Paths.get(UPLOAD_DIR + file.getOriginalFilename()); Files.write(path, bytes); return new ResponseEntity<>("File uploaded successfully", HttpStatus.OK); } catch (IOException e) { e.printStackTrace(); return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } } ``` #### 调试日志记录 增加必要的调试语句或启用框架级别的日志输出可以帮助定位具体原因所在。例如,可以在控制台打印出每次请求携带的数据信息以便更好地理解实际发生了什么情况[^4]。 ```java import org.slf4j.Logger; import org.slf4j.LoggerFactory; private static final Logger logger = LoggerFactory.getLogger(FileUploadController.class); // Inside the handler method... logger.debug("Received request with content-type header: {}", request.getHeader("Content-Type")); logger.info("Uploading file '{}' ({}/{})", file.getName(), NumberFormat.getInstance().format(file.getSize()), file.getContentType() != null ? file.getContentType() : "unknown"); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

luffy5459

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值