春天如何上传文件? [英] How to upload file in spring?

查看:63
本文介绍了春天如何上传文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法在spring controller中获取文件名

I am not able to get the file name in spring controller

<form:form method="post" modelAttribute="sampleDetails" 
 enctype="multipart/form-data">
    <input type="file" name="uploadedFileName" id="fileToUpload" required="" >
    <input type="submit" name="import_file" value="Import File" id="" />
</form:form>

它是我在控制器中的post方法

Its my post method in controller

@RequestMapping(method = RequestMethod.POST)
public String importQuestion(@Valid @RequestParam("uploadedFileName") 
MultipartFile multipart, @ModelAttribute("sampleDetails") SampleDocumentPojo sampleDocument,  BindingResult result, ModelMap model) {
    logger.debug("Post method of uploaded Questions ");

    logger.debug("Uploaded file Name : " + multipart.getName());
    return "importQuestion";
}

提交后收到警告消息.

 warning [http-nio-8080-exec-9] WARN 
 org.springframework.web.servlet.PageNotFound - Request method 'POST' not 
 supported
 [http-nio-8080-exec-9] WARN 
 org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver 
 - Handler execution resulted in exception: Request method 'POST' not 
 supported

推荐答案

在您的控制器中,您需要指定要使用mutlipart

in your controller you need to specify that you are expecting mutlipart

使用

consumes = {"multipart/form-data"}

并使用getOriginalFileName()生成文件名

and to ge the file name using getOriginalFileName()

@RequestMapping(method = RequestMethod.POST, consumes = {"multipart/form-data"})
public String importQuestion(@Valid @RequestParam("uploadedFileName") 
MultipartFile multipart,  BindingResult result, ModelMap model) {
   logger.debug("Post method of uploaded Questions ");

    logger.debug("Uploaded file Name : " + multipart.getOriginalFilename());
   return "importQuestion";
}

也在您的html中,类型文件输入的名称应与RequestParam"uploadedFileName"相同

Also in your html the name of your input of type file should be the same as the RequestParam "uploadedFileName"

     <input type="file" name="uploadFileName" id="fileToUpload" required="" >

将其更改为

  <input type="file" name="uploadedFileName" id="fileToUpload" required="" >

这篇关于春天如何上传文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆