我是Java的初学者并且去创建一个Web应用程序。我正在使用ajaxform向控制器提交一个表单。元素很少,其中一个是type=file
。
我的控制器方法如下
@RequestMapping(value = { "/addReplies" }, method = {
org.springframework.web.bind.annotation.RequestMethod.POST,
org.springframework.web.bind.annotation.RequestMethod.GET } )
@ResponseBody
public Map<String,Object> addReplies(
@Valid @ModelAttribute("Replies") Replies replies,
BindingResult result, HttpServletRequest request,
HttpServletResponse response,Locale locale,Principal principal,
@RequestParam(value = "fileData2",required=false) CommonsMultipartFile fileData2[]) throws ServletException,
IOException {
//perform some opraton
}
如果数据中有附件可用,则一切正常,否则不会进入此方法。
如果我从方法中移除@RequestParam(value = "fileData2",required=false) CommonsMultipartFile fileData2[]
此参数,那么效果不错,但通过这种方式我无法获得附件。
请尽量了解我的问题,并尽快给我一切可能的解决方案。
如果我不使用ajax并使用regul
提交表单,则此方法运行良好答案 0 :(得分:3)
要正常上传文件,您需要在表单中使用encType =“multipart / form-data”。如果你想使用Ajax上传文件,你需要使用它的方法
或
您要上传文件,在序列化ajaxForm之前首先检查它是否为filepart为null,如果为null,则禁用该元素以获得更长的可用性并提交
beforeSerialize: function($form, options){
//before serializing the data have to disable element if the data is not avaliable
$(".attachfile").filter(function(){
return !this.value; }).attr("disabled", "disabled");
},
答案 1 :(得分:2)
我也是这样做的 但我的编码也在工作
做这个解决方案
@RequestMapping(value="/saveUserTask", method=RequestMethod.POST)
@ResponseBody
public Map<String,String> saveUserTask(
@RequestParam( value = "title" , required = false) String title,
@RequestParam( value = "projectid" , required = false) int projectid,
@RequestParam( value = "mileid" , required = false,defaultValue ="-1") int mileid,
@RequestParam( value = "responsible" , required = false) int responsible[],
@RequestParam( value = "startDate" , required = false) Date startDate,
@RequestParam( value = "endDate" , required = false) Date endDate,
@RequestParam( value = "description" , required = false) String description,
@RequestParam( value = "priority" , required = false, defaultValue="1") int priority,
@RequestParam( value = "workHours" , required = false) int workHours,
@RequestParam(value = "attachment" , required = false) MultipartFile myFile,
HttpServletRequest request,Principal principal,RedirectAttributes redirectAttributes,Locale locale) throws ParseException, IOException{
String fileAttachPath;
if(myFile!=null)
fileAttachPath=request.getSession().getServletContext().getRealPath("/WEB-INF/attechments/"+ new Date().getTime() + "_" + myFile.getOriginalFilename());
else
fileAttachPath="";
}
答案 2 :(得分:2)
您之前是否尝试过提交ajax表单数据对象?
@RequestMapping(value ="/settingsSim",method=RequestMethod.POST)
@ResponseBody
public Map uploadSimSettings(@RequestBody String body) {
/*
some controller logic
*/
}
答案 3 :(得分:1)
我刚刚这样做了:
$("#myform").bind('ajax:complete', function() {
// tasks to do with ajax submit
});
事情很完美。
有关更具体的详细信息,请参阅此api documentation。