SpringBoot实现文件上传,附带表单数据!

在springboot2.0以后文件上传的依赖spring已经自动帮我导入了,我们直接开整。

在这里插入图片描述
我们先创建上传后的路径

html页面:

<form action="/T_paper/addT_paper" id="info" method="post" enctype="multipart/form-data">
				<table>
					<tr>
						<td>论文题目:</td>
						<td><input type="text" id="ti" name="title"></td>
						<td id="te" style="color: red"></td>
					</tr>
					<tr>
						<td>类型:</td>
						<td><select name="t_type.typeCode">
								<option th:each="t : ${type}" th:text="${t.typeName}"
									th:value="${t.typeCode}"></option></td>
					</tr>
					<tr>
						<td>论文摘要:</td>
						<td><input type="text" id="paperSummary" name="paperSummary"></td>
						<td id="te1" style="color: red"></td>
					</tr>
					<tr>
						<td>论文内容:</td>
						<td><input type="file" id="paperPath" name="filename"/></td>
						<td id="te2" style="color: red">上传大小不能超过5M*上传文件类型必须为:doc docx</td>
					</tr>
					<tr>
						<td><input type="submit" value="保存"> </td>
						<td><input type="button" id="fh" value="返回"/></td>
					</tr>
				</table>
			</form>

记得一定要加
在这里插入图片描述
如果需要进行对文件格式判和大小判断就要写jquery了

$("#info").submit(function() {
			var title = $("#ti").val();
			var paperSummary=$("#paperSummary").val();
			var paperPath=$("#paperPath").val();//获取文件
			var point = paperPath.lastIndexOf(".");  
			var type = paperPath.substr(point);//获取后缀
			var fileSzie=$("#paperPath")[0].files[0].size;//获取文件大小,得到的值为字节类型
			var judge=true;
			if(title==""){
				$("#te").html("论文标题不能为空")
				judge= false;
			}
			if(paperSummary==""){
				$("#te1").html("摘要不能为空")
				judge=false;
			}
			if(paperPath==""||type!=".doc"||type!=".doc"||fileSzie>1000){
				$("#te2").html("上传文件格式不正确")
				judge=false;
			}else{
				$("#te2").html("")
			}
			return judge;
		})

controller:

@RequestMapping("addT_paper")
	public String addT_paper(T_paper t_paper,@RequestParam("filename")MultipartFile file){
		  // 获取文件名
        String fileName = file.getOriginalFilename();

        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 文件上传路径
        String filePath = "D:\\springboot\\PaperManage\\src\\main\\resources\\static\\FileUpload\\";
        // 解决中文问题,liunx 下中文路径,图片显示问题
        //fileName = UUID.randomUUID() + suffixName;
        File dest = new File(filePath + fileName);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            //上传
            file.transferTo(dest);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
		t_paper.setPaperPath(filePath+fileName);
		
		service.addT_paper(t_paper);
		return "redirect:pageInfo";
	}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值