MultipartFile上传多个文件

该博客介绍了如何在Spring中处理MultipartFile类型的参数,通过一个表单接收多个文件上传,然后利用UploadUtils工具类进行文件存储,并在上传成功后更新相关业务数据。在Controller中,接收到请求后,根据任务ID和用户ID更新Result表的提交状态。

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

j.jsp页面:

    <form method="post" class="form-x" action="upload" enctype="multipart/form-data">  

Controller:

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String upload(HttpServletRequest request,
@RequestParam(value="taskid") int taskid,  //参数名与页面中的name相同
@RequestParam(value = "uploadfile", required = false) MultipartFile[] uploadfile)
{
String currentID=(String) request.getSession().getAttribute("id");
String road=Config.task+taskid+"/"+currentID;
UploadUtils up = new UploadUtils();
if(up.uploadUtils(uploadfile, road))
{
//获得当前用户id
System.out.println("$$$$$"+taskid);
//根据作业ID,和用户ID。修改result表中的submit状态
Result result = new Result();
result.setStuId(currentID);
result.setTaskId(taskid);
result.setSubmit(true);
try {
resultService.updateResult(result);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return"redirect:/joblist";  //返回作业列表

}


工具类中的函数:

//上传,road是文件存放路径

public boolean uploadUtils(MultipartFile[] uploadfile,String road)
{
if(uploadfile!=null && uploadfile.length > 0) 
{
for(MultipartFile file:uploadfile)
{

//设置上传文件位置
        String uploadpath = file.getOriginalFilename();  //获取文件名
        System.out.println("hahahah"+uploadpath);  
               //创建文件夹
           File uploadtargetFile = new File(road,uploadpath);
//判断文件是否存在
           isExists(uploadtargetFile);
//保存文件
if (saveFile(file, uploadtargetFile)) 
{
return true;
}
else
{
return false;
}
   
}

}
return false;
}

//判断该路径下文件是否存在
private boolean isExists(File uploadtargetFile)
{
if (!uploadtargetFile.exists())
   {
    uploadtargetFile.mkdirs(); 
    return true;
}
   else{
    System.out.println("文件已存在");
    return false;
   }
}

//保存文件
private boolean saveFile(MultipartFile file, File uploadtargetFile)
{  
       // 判断文件是否为空  
       if (!file.isEmpty()) {  
           try {  
           file.transferTo(uploadtargetFile);  //写入文件
               return true;  
           } catch (Exception e) {  
               e.printStackTrace();  
           }  
       }  
       return false;  
   }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值