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));
        }
    }
相关推荐
2301_822366354 分钟前
C++中的命令模式变体
开发语言·c++·算法
一刻钟.6 分钟前
C#高级语法之线程与任务
开发语言·c#
csdn2015_17 分钟前
MyBatis Generator 核心配置文件 generatorConfig.xml 完整配置项说明
java·mybatis
追逐梦想的张小年20 分钟前
JUC编程03
java·开发语言·idea
派葛穆22 分钟前
Python-PyQt5 安装与配置教程
开发语言·python·qt
万邦科技Lafite29 分钟前
一键获取京东商品评论信息,item_reviewAPI接口指南
java·服务器·数据库·开放api·淘宝开放平台·京东开放平台
小乔的编程内容分享站30 分钟前
记录使用VSCode调试含scanf()的C语言程序出现的两个问题
c语言·开发语言·笔记·vscode
indexsunny40 分钟前
互联网大厂Java面试实战:从Spring Boot到微服务架构的技术问答解析
java·spring boot·redis·微服务·kafka·jwt·flyway
toooooop841 分钟前
php BC MATH扩展函数计算精度-第三个参数
开发语言·php