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));
        }
    }
相关推荐
VX_bysjlw98511 分钟前
基于协同过滤的美食推荐系统的设计与实现32221-计算机毕设原创(免费领源码+带部署教程)
java·spring boot·redis·mysql·tomcat·maven·mybatis
星夜离尘5624 分钟前
MATLAB 只剩批次摘要怎么合并方差:用 n、mean、M2 保留批间差异
开发语言·matlab
Misnice26 分钟前
Python 的数据类型
java·windows·python
yuniko-n42 分钟前
【JUC】JMM(Java 内存模型)
java·开发语言
十碗饭吃不饱43 分钟前
MySQL InnoDB RR 隔离下二级索引临键锁引发 INSERT 锁超时 全链路解析
java·数据库·mysql
专业程序开发源1 小时前
springboot校企合作双选会一站式预约与面试系统16010-计算机课程设计、毕业设计
java·vue.js·spring boot·后端·面试·php·课程设计
Elastic 中国社区官方博客1 小时前
Observability:当 YAML 遇上 IConfiguration:OpenTelemetry .NET SDK 的声明式配置
大数据·开发语言·elasticsearch·搜索引擎·全文检索·.net
郑州光合科技余经理2 小时前
同城商城源码:商品库和订单库怎么随包交付
android·java·开发语言·后端·uni-app·php·ai编程