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));
        }
    }
相关推荐
Sunshine for you26 分钟前
C++中的职责链模式实战
开发语言·c++·算法
@我漫长的孤独流浪39 分钟前
Python编程核心知识点速览
开发语言·数据库·python
qq_416018721 小时前
C++中的状态模式
开发语言·c++·算法
2401_884563241 小时前
模板代码生成工具
开发语言·c++·算法
code 小楊1 小时前
yrb 1.5.0 正式发布:Python 极简国内下载加速与全景可视化终端体验!
开发语言·python
2401_831920741 小时前
C++代码国际化支持
开发语言·c++·算法
2401_851272991 小时前
自定义内存检测工具
开发语言·c++·算法
章鱼丸-2 小时前
DAY31 文件的拆分和写法
开发语言·python
左左右右左右摇晃2 小时前
Java并发——synchronized锁
java·开发语言
☆5662 小时前
C++中的命令模式
开发语言·c++·算法