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

前端使用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();
   }
  }
 }
}

 

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

附:ConfigUtil的path()方法:

public  String path(){
		Properties properties = new Properties();
		String filePath = null;
		try {
//路径再配置文件中进行配置
			properties.load(this.getClass().getResourceAsStream("/conf/path.properties"));
			String path = properties.getProperty("path");
			String dir = properties.getProperty("firPath");
			filePath = path+File.separator+dir;
			return filePath;
		} catch (IOException e) {
			filePath = "修改目录";
			e.printStackTrace();
		}
		return filePath;
	}

 

  • 4
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值