formData web页面上传单(多)文件到服务器并本地保存

本文介绍了一个使用HTML、JavaScript和SpringBoot实现的文件上传功能。通过前端的form表单收集文件,利用FormData对象发送POST请求,并在后端进行文件的保存处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

formData web页面上传单(多)文件到服务器并本地保存

html代码

<div style="margin-top: 20px;">
	<span class="input-title">文件1:</span>
	<input id="file1" type="file" style="display:inline-block; margin-left:10px;">
</div>

<div style="margin-top: 20px;">
	<span class="input-title">文件2:</span>
	<input id="file2" type="file" style="display:inline-block; margin-left:10px;">
</div>

<div style="margin-top: 20px;">
	<span class="input-title"></span>
	<button type="button" class="btn button-blue" style="color: #ffffff;margin-left: 10px;" id="submit_btn">提交</button>
</div>

js代码

$("#submit_wxsh_bind_btn").click(function () {
	var param = "testStr";
	var formData = new FormData();
	formData.append('files', $('#file1')[0].files[0]);
	formData.append('files', $('#file2')[0].files[0]);
	formData.append('param', param); // 其他参数
    
	var url = reqUrl + '?key=' + skit.get('key');
    
	$.ajax({
        url: url,
        type: 'POST',
        data: formData,
        cache: false,
        processData: false,
        contentType: false
    }).done(function(resp) {
    	// do something
    }).fail(function(resp) {
    	//do something
    });
});

java代码(SpringBoot)

public String wxoabind(String key, @RequestParam MultipartFile[] files, @RequestParam String param) throws IOException {
	// @RequestParam MultipartFile[] files---单个文件时 @RequestParam MultipartFile file接收即可
	String realPath = CommonUtil.getRealPath();
	
	for(MultipartFile file:files) {
		String fileName = file.getOriginalFilename();
		File outputFile = new File(realPath + File.separator + ".." + File.separator +
	            ".." + File.separator + "testDir" + File.separator + fileName);
		
		if(!outputFile.getParentFile().exists()) {
			outputFile.getParentFile().mkdirs();
	    }
		
		outputFile.createNewFile();
		file.transferTo(outputFile); 
	}
	
	JSONObject respObj = null;
    String respContent = "{'errcode': 0,'errmsg':\"success\"}";

    respObj = JSONObject.fromObject(respContent);
    return respObj.toString();
}

效果图
页面效果图
选择文件后
上传完成

在koa2中,可以使用formidable模块来接收formdata类型的文件上传请求,文件复制保存本地。具体步骤如下: 1. 安装formidable模块,执行命令:npm install formidable 2. 在koa2的路由处理函数中,使用formidable来解析请求中的formdata数据,文件保存本地。示例代码如下: ``` const Koa = require(&#39;koa&#39;); const Router = require(&#39;koa-router&#39;); const formidable = require(&#39;formidable&#39;); const fs = require(&#39;fs&#39;); const path = require(&#39;path&#39;); const app = new Koa(); const router = new Router(); router.post(&#39;/upload&#39;, async (ctx) => { // 创建formidable表单解析器 const form = new formidable.IncomingForm(); // 设置上传目录 form.uploadDir = path.join(__dirname, &#39;uploads&#39;); // 保留上传文件的扩展名 form.keepExtensions = true; // 解析请求中的formdata数据 const { files } = await new Promise((resolve, reject) => { form.parse(ctx.req, (err, fields, files) => { if (err) { reject(err); } else { resolve({ fields, files }); } }); }); // 将文件保存本地 const { path: filePath, name } = files.file; const newFilePath = path.join(form.uploadDir, name); fs.copyFileSync(filePath, newFilePath); // 返回上传成功消息 ctx.body = &#39;上传成功&#39;; }); app.use(router.routes()).use(router.allowedMethods()); app.listen(3000, () => { console.log(&#39;server is running at http://localhost:3000&#39;); }); ``` 在上述代码中,我们首先创建了一个formidable表单解析器,设置了上传目录和保留上传文件的扩展名的选项。然后,我们调用form.parse方法来解析请求中的formdata数据,将解析结果保存在files变量中。接着,我们将上传的文件复制保存本地,最后返回上传成功消息。注意,在koa2中,我们需要使用await关键字来等待form.parse方法的返回结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值