springmvc文件上传

文件上传种类

1.Java后端代码(使用Servlet):

java 复制代码
@WebServlet("/upload")
public class FileUploadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取上传的文件
        Part filePart = request.getPart("file");
        String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix.
        InputStream fileContent = filePart.getInputStream();

        // 保存文件到服务器
        OutputStream out = new FileOutputStream(new File("/path/to/upload/" + fileName));
        int read = 0;
        byte[] bytes = new byte[1024];

        out = new FileOutputStream(new File("/path/to/upload/" + fileName));
        while ((read = fileContent.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }
        out.flush();
        out.close();
    }
}

2.Spring Boot后端代码:

java 复制代码
@RestController
public class FileUploadController {

    @PostMapping("/upload")
    public String handleFileUpload(@RequestParam("file") MultipartFile file) {
        if (!file.isEmpty()) {
            try {
                // 获取文件名
                String fileName = file.getOriginalFilename();
                // 保存文件到服务器
                File dest = new File("/path/to/upload/" + fileName);
                file.transferTo(dest);
                return "File uploaded successfully: " + fileName;
            } catch (Exception e) {
                return "File upload failed: " + e.getMessage();
            }
        } else {
            return "File is empty";
        }
    }
}

3.Node.js后端代码:

java 复制代码
const express = require('express');
const multer = require('multer');
const app = express();
const port = 3000;

// 设置文件存储
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, '/path/to/upload/');
    },
    filename: function (req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
    }
});

const upload = multer({ storage: storage });

app.post('/upload', upload.single('file'), (req, res) => {
    res.send('File uploaded successfully.');
});

app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}/`);
});

4.批量上传

java 复制代码
@Controller
@RequestMapping("/user")//根据这个地址区分访问哪个模块 http://localhost:8080/user/xxx
public class UserController {
    //批量上传:把前端同时选中的多个文件,一股脑保存到 C:\\upload 目录,并在控制台打印用户名。
    @RequestMapping(value = "/quick23")
    @ResponseBody
    public void save23(String username, MultipartFile[] uploadFile) throws IOException {
        System.out.println(username);
        for (MultipartFile multipartFile : uploadFile) {
            String originalFilename = multipartFile.getOriginalFilename();
            multipartFile.transferTo(new File("C:\\upload\\" + originalFilename));
        }
    }
相关推荐
AI人工智能+电脑小能手3 分钟前
【大白话说Java面试题 第114题】【并发篇】第14题:说一下悲观锁的优点和缺点?
java·开发语言·面试
盒马盒马5 分钟前
Rust:Vec
开发语言·rust
让我上个超影吧6 分钟前
Claude Code 源码看 Agent 系统设计
java·ai·ai编程
plainGeekDev7 分钟前
网络状态监听 → ConnectivityManager + Flow
android·java·kotlin
devilnumber8 分钟前
Java 迭代器(Iterator)完全指南:从入门到实战
java·开发语言·迭代器
罗超驿9 分钟前
13.Java多线程进阶:手动实现线程池与定时器机制详解
开发语言·面试·javaee
qq_1958216510 分钟前
6. 应用层协议实现:CoE协议栈集成、对象字典配置、PDO映射
java·服务器·网络
弹简特13 分钟前
【Java项目-轻聊】10-实现会话管理模块
java·开发语言·数据库
人道领域14 分钟前
Java后端开发者转型AIAgent开发路线指南
java·开发语言
许彰午16 分钟前
36_Java设计模式之代理模式
java·设计模式·代理模式