springboot 接收文件

package cn.juhe.controller;

import net.sf.json.JSONObject;
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 org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

@RestController
public class UploadTest {
    /**
     * 接受未知参数名的多个文件或者一个文件
     *
     * @param request 请求
     * @return 返回
     */
    @PostMapping("/upload")
    public JSONObject handleFileUpload(HttpServletRequest request) {
        Iterator<String> fileNames = ((MultipartHttpServletRequest) request).getFileNames();
        JSONObject result = null;
        while (fileNames.hasNext()) {
            String next = fileNames.next();
            MultipartFile file = ((MultipartHttpServletRequest) request).getFile(next);
            System.out.println("file.getName():" + file.getName());
            System.out.println("file.getOriginalFilename():" + file.getOriginalFilename());
            String folder = "E:\\upload\\received\\";
            String picName = new Date().getTime() + ".jpg";
            File filelocal = new File(folder, picName);
            result = new JSONObject();
            result.put(picName, folder + picName);
            try {
                file.transferTo(filelocal);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("error_code", 223805);
        jsonObject.put("reason", "文件过大或上传发生错误");
        Random random = new Random();
        if (random.nextInt(10) > 3) {
            jsonObject.put("error_code", 0);
            jsonObject.put("reason", "success");

            jsonObject.put("result", result);
        }
        return jsonObject;
    }

    /**
     * 知道参数名的文件上传
     *
     * @param multipartFile 文件
     * @return 返回
     * @throws IOException
     */
    @PostMapping("/uploadCommon")
    //public JSONObject upload(MultipartFile multipartFile) throws IOException {
    public JSONObject upload(@RequestParam("A") MultipartFile multipartFile) throws IOException {
        String name = multipartFile.getName();//上传文件的参数名
        String originalFilename = multipartFile.getOriginalFilename();//上传文件的文件路径名
        long size = multipartFile.getSize();//文件大小
        String folder = "E:\\upload\\received\\";
        String picName = new Date().getTime() + ".jpg";
        File filelocal = new File(folder, picName);
        multipartFile.transferTo(filelocal);
       /* {
            "reason": "success",
                "result": {
            "D": "/upload/order/files/2016/a72750ad-8950-4949-b04a-37e69aff0d23.jpg",
                    "A": "/upload/order/files/2016/6842811a-eb76-453b-a2f3-488e2bb4500e.jpg",
                    "B": "/upload/order/files/2016/ccc96347-3cb8-4e2e-99a3-0c697b57eb88.jpg",
                    "C": "/upload/order/files/2016/d470d533-a54b-406a-a0f9-bbf82c314755.jpg"
        },
            "error_code": 0
        }*/
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("error_code", 223805);
        jsonObject.put("reason", "文件过大或上传发生错误");
        Random random = new Random();
        if (random.nextInt(10) > 3) {
            jsonObject.put("error_code", 0);
            jsonObject.put("reason", "success");
            JSONObject result = new JSONObject();
            result.put(name, folder + picName);
            jsonObject.put("result", result);
        }
        return jsonObject;
    }
}

 

### Spring Boot 实现文件上传功能 #### 使用 `MultipartFile` 类处理文件上传请求 为了在Spring Boot应用程序中实现文件上传,主要依赖于Spring框架提供的`MultipartFile`接口。当客户端发送带有文件的HTTP POST请求时,服务器端可以通过此接口获取到上传的文件对象,并对其进行保存或其他操作[^1]。 ```java import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; @RestController public class FileUploadController { @PostMapping("/upload") public String handleFileUpload(@RequestParam("file") MultipartFile file){ if (file.isEmpty()) { return "Failed to upload empty file."; } try { // Save the file on server... byte[] bytes = file.getBytes(); Path path = Paths.get(UPLOAD_FOLDER + file.getOriginalFilename()); Files.write(path, bytes); return "You successfully uploaded '" + file.getOriginalFilename() + "'"; } catch (IOException e) { return "Failed to upload '" + file.getOriginalFilename() + "' => " + e.getMessage(); } } } ``` 上述代码展示了基本的文件接收逻辑,其中包含了检查文件是否为空以及尝试将接收到的数据写入指定位置的过程[^2]。 #### 配置多部分(Multipart)解析器 为了让Spring能够正确解析来自表单数据中的文件输入项,在配置文件application.properties或application.yml内需设置multipart属性: 对于properties格式: ```properties spring.servlet.multipart.max-file-size=10MB spring.servlet.multipart.max-request-size=10MB ``` YAML格式则如下所示: ```yaml spring: servlet: multipart: max-file-size: 10MB max-request-size: 10MB ``` 这些参数用于控制允许的最大单个文件大小及整个请求体尺寸限制[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

micro_cloud_fly

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

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

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

打赏作者

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

抵扣说明:

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

余额充值