SSM-后端接收前端传递的文件

来源:互联网 发布:单片机方案开发 编辑:程序博客网 时间:2024/05/22 03:17

前端使用ajax,以文件作为参数发送到后端,后端需要的处理:

控制层需要对前端传来的文件进行处理:

public class vrDrivenTestController {

 //JSON形式返回给结果
 @ResponseBody
 //文件只能用POST方式进行传递
 @RequestMapping(value = "/upload", method = RequestMethod.POST)

 public void filesUpload(HttpServletRequest request, HttpServletResponse response,
   @RequestParam("file") MultipartFile file, @RequestParam("user_name") String user_name,
   @RequestParam("user_id") String user_id, @RequestParam("region_name") String region_name,
   @RequestParam("region_id") Float region_id) {

  //设置返回信息的编码格式及类型
  response.setCharacterEncoding("UTF-8");
  response.setContentType("application/json;charset=utf-8");
  String callbackName = request.getParameter("callback");

  JSONObject json = new JSONObject();
  JSONArray array = new JSONArray();
  JSONObject resultJson = new JSONObject();

  // 获取文件名
  String filename = file.getOriginalFilename();
  // 判断文件是否为空
  if (!file.isEmpty()) {
   try {
    // 传入的文件保存的路径,如果没有先进行创建文件
    ConfigUtil configUtil = new ConfigUtil();
    String FilePath = configUtil.path() + File.separator + filename;
    File dir = new File(FilePath);
    if (!dir.exists()) {
     dir.mkdirs();
    }
    // 转存文件,否则所创建的是个文件夹
    file.transferTo(new File(FilePath));
    // 获取需要处理的文件
    resultJson.put("data", "成功");
    response.getWriter().write(callbackName + "([" + resultJson + "])");
   } catch (Exception e) {
    System.out.println("文件转存失败");
   }
  } else {
   try {
    resultJson.put("data", "空文件");
    response.getWriter().write(callbackName + "([" + resultJson + "])");
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }
}

注:虽然前端传文件到后端对文件大小没有限制,但是针对具体的业务应该是在前端对文件大小进行一个限制。