Java中上传文件和表单数据提交如何质莸
2018-06-19 · 国内最优秀java资源共享平台
关注
展开全部
//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 "上传失败,因为文件是空的.";
}
}
//注:上传文件的表单,需要将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 "上传失败,因为文件是空的.";
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询