html表单提交带后台,带图片上传的表单提交到后台接收过程

//创建一个下载的方法,需要时调用

private void upload(HttpServletRequest request, HttpServletResponse response) {

//1.创建一个磁盘工厂对象

DiskFileItemFactory factory = new DiskFileItemFactory();

//2.通过工厂对象创建上传对象

ServletFileUpload fUpload = new ServletFileUpload(factory);

//3.通过上传对象解析前端发送的复合型表单数据

List list = null;

HashMap map = new HashMap<>();

Student student = new Student();

try {

//通过上传对象解析请求中的数据,获得集合

list = fUpload.parseRequest(request);

for (FileItem fItem:list) {

//判断是否非文本信息

if(!fItem.isFormField()){

//2.修改上传图片的名字

//使用UUID--生成唯一的ID值---wehfiw123%@#$!6fwef_f.jpg

UUID uuid = UUID.randomUUID();

System.out.println(uuid.toString());

String path = getServletContext().getRealPath("Upload");

File file = new File(path);

if(!file.exists()){

file.mkdirs();

}

//拼接路径和图片名字(uuid生成的随机字符串拼接上图片名字)

File file1 = new File(file, uuid.toString() + "_" + fItem.getName());

IOUtils.copy(fItem.getInputStream(),new FileOutputStream(file1));

//存储的路径不能为绝对路径

student.setImgUrl("Upload/"+uuid.toString() + "_" + fItem.getName());

}else{

//通过key(getFieldNmae--表单的name属性值)获取value(getString--表单的value值)

String value = map.get(fItem.getFieldName());

//第一次存储

if(value == null){

map.put(fItem.getFieldName(),fItem.getString());

}else{//多次存储(多选框)

map.put(fItem.getFieldName(),value+","+fItem.getString());

}

}

}

//利用该方法把map集合的数据存放到student对象中

BeanUtils.populate(student,map);

request.setAttribute("stu",student);

request.getRequestDispatcher("show.jsp").forward(request,response);

} catch (FileUploadException e) {

e.printStackTrace();

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} catch (IllegalAccessException e) {

e.printStackTrace();

} catch (InvocationTargetException e) {

e.printStackTrace();

} catch (ServletException e) {

e.printStackTrace();

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值