当我尝试上传数据以及附加的文件时,我有一个控制器发布方法。它工作正常。 但是我想知道在没有附加文件时如何处理以及如何读取数据。 这是我的控制器:
@RequestMapping(value="saveimage",method=RequestMethod.POST)
public ModelAndView saveimage( @RequestParam CommonsMultipartFile file,HttpSession session,HttpServletRequest request,HttpServletResponse response) throws Exception
{
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(THRESHOLD_SIZE);
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
ServletContext context = session.getServletContext();
String uploadPath = context.getRealPath(UPLOAD_DIRECTORY);
System.out.println(uploadPath);
System.out.println(file.getOriginalFilename());
byte[] bytes = file.getBytes();
BufferedOutputStream stream =new BufferedOutputStream(new FileOutputStream(new File(uploadPath + File.separator + file.getOriginalFilename())));
stream.write(bytes);
stream.flush();
stream.close();
EmpFileBean e=new EmpFileBean();
e.setFile(file.getOriginalFilename());
e.setTextdata(request.getParameter("textdata"));
dao.saveImage(e);
request.setAttribute("img_name", e.getFile());
return new ModelAndView("uploadform","filesuccess","File successfully saved!");
}
我的JSP看起来像:
<form:form method="post" action="saveimage" attribute="EmpFileBean"
enctype="multipart/form-data">
<p><label for="image">Choose Image</label></p>
<p><input name="file" id="fileToUpload" type="file" path="file"/></p>
<p><label for="textdata">Enter User Name</label></p>
<p><input name="textdata" id="textdata" type="text" path="textdata"/></p>
<%
if(request.getAttribute("img_name")!=null)
{
%>
<img alt="" src="images/<%=request.getAttribute("img_name")%>">
<%} %>
<p><input type="submit" value="Upload"></p>
</form:form>
答案 0 :(得分:0)
如果您使用@RequestParam
进行多部分文件上传,那么如果该字段为空,则控制器不接受请求,说明某些错误消息
请求中不存在参数“file”,如:
但是,您可以将Model类用作@ModelAttribute
,并在模型类中放置多部分文件对象及其setter
,getter
。也许这个类看起来像那样,
public class FileBean {
private CommonsMultipartFile file;
public CommonsMultipartFile getFile() {
return file;
}
public void setFile(CommonsMultipartFile file) {
this.file = file;
}
}
来自控制器
@RequestMapping(value="saveimage",method=RequestMethod.POST)
public ModelAndView saveimage( @ModelAttribute FileBean file,HttpSession session,HttpServletRequest request,HttpServletResponse response) throws Exception{
----------------------- your controller code---------
}
让我知道状态。