在 Spring MVC 中实现 File Uploader 控制器时,我遇到了一个问题。我的代码快照如下。
@Controller
public class FileUploader extends AbstractBaseController implements HandlerExceptionResolver
{
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
@ResponseBody
public JSONObject handleFileUpload(@RequestParam("file") MultipartFile file)
{
JSONObject returnObj = new JSONObject();
if (file.isEmpty())
{
returnObj.put("success", "false");
returnObj.put("message", "File is empty");
}
else
{
try
{
//my file upload logic goes here
}
catch (Exception e)
{
returnObj.put("success", "false");
returnObj.put("message", "File not uploaded.");
}
}
return returnObj;
}
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object obj, Exception exception)
{
ModelAndView model = new ModelAndView();
Map map = new HashMap();
if (exception instanceof MaxUploadSizeExceededException)
{
// I want to return JSONObject from here like given below.
/**
* { "message":"File size exceeded", "success":"false" }
* */
map.put("message", "File size exceeded");
map.put("success", "false");
model.addObject(map);
}
return model;
}
}
我的弹簧配置看起来像
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver" >
<property name="maxUploadSize" value="300000"/>
</bean>
现在在我的控制器中,我想在我的控制器中的 resolveException 方法中返回 JSONObject 而不是 ModelAndView,如代码快照中给出的那样,因为我正在开发一些类似 REST 的方法来上传文件。
有任何想法吗?谢谢