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));
        }
    }
相关推荐
星空露珠6 分钟前
迷你世界UGc3.0脚本Wiki[剧情动画模块管理接口 Timeline]
开发语言·数据结构·算法·游戏·lua
格子软件11 分钟前
2026年分布式GEO代理流量调度:源码级状态机防重挂实战
java·vue.js·人工智能·spring boot·分布式·vue
hj28625113 分钟前
Docker 容器化技术标准化笔记
java·笔记·docker
未来之窗软件服务21 分钟前
计算机考试-C语言 应用题—东方仙盟
c语言·开发语言·仙盟创梦ide·东方仙盟·计算机考试
想你依然心痛22 分钟前
AtomCode在后端开发中的实战体验:Go微服务从零搭建
开发语言·微服务·golang
我是一颗柠檬24 分钟前
【Java项目技术亮点】EXPLAIN深度分析与慢查询治理
android·java·开发语言
万亿少女的梦16827 分钟前
基于Spring Boot的社区管理系统设计与实现
java·spring boot·mysql·vue·系统设计
luj_176829 分钟前
草酸与烟酸对消化及糖代谢的影响解析
服务器·c语言·开发语言·经验分享·算法
fei_sun34 分钟前
【SystemVerilog】SystemVerilog与C语言的接口
c语言·开发语言
大气的小蜜蜂37 分钟前
领域层的服务
java·前端·数据库