java fileItem如何遍历上传普通表单域值到数据库?

java fileItem如何遍历上传普通表单域值到数据库?,第1张

//1.form表单

//注:上传文件的表单,需要将form标签设置enctype="multipart/form-data"属性,意思是将Content-Type设置成multipart/form-data

<form action="xxx" method="post" enctype="multipart/form-data">

<input type="text" name="name" id="id1" /><br />

<input type="password" name="password" /><br />

<input type="file" name="file" value="选择文件"/><input id="submit_form" type="submit" value="提交"/>

//1.form表单

//注:上传文件的表单,需要将form标签设置enctype="multipart/form-data"属性,意思是将Content-Type设置成multipart/form-data

<form action="xxx" method="post" enctype="multipart/form-data">

<input type="text" name="name" id="id1" /><br />

<input type="password" name="password" /> <br />

<input type="file" name="file" value="选择文件"/><input id="submit_form" type="submit" value="提交"/>

</form>

//2.servlet实现文件接收的功能

boolean isMultipart = ServletFileUpload.isMultipartContent(request)//判断是否是表单文件类型

DiskFileItemFactory factory = new DiskFileItemFactory()

ServletFileUpload sfu = new ServletFileUpload(factory)

List items = sfu.parseRequest(request)//从request得到所有上传域的列表

for(Iterator iter = items.iterator()iter.hasNext()){

FileItem fileitem =(FileItem) iter.next() if(!fileitem.isFormField()&&fileitem!=null){

//判读不是普通表单域即是file

System.out.println("name:"+fileitem.getName())

}

}

3.扩展一下springboot

@RequestMapping("/xxx")

@ResponseBody

public String handleFileUpload(@RequestParam("file") MultipartFile file) {

if (!file.isEmpty()) {

try {

BufferedOutputStream out = new BufferedOutputStream(

new FileOutputStream(new File(

file.getOriginalFilename())))

System.out.println(file.getName())

out.write(file.getBytes())

out.flush()

out.close()

} catch (FileNotFoundException e) {

e.printStackTrace()

return "上传失败," + e.getMessage()

} catch (IOException e) {

e.printStackTrace()

return "上传失败," + e.getMessage()

}

return "上传成功"

} else {

return "上传失败,因为文件是空的."

}

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/tougao/11583111.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-17
下一篇 2023-05-17

发表评论

登录后才能评论

评论列表(0条)

保存