Java-servlet-获取所有请求参数

1> 请求参数

@RequestMapping(value = "/api", method = RequestMethod.POST)
@ApiOperation(value = "apivalue", notes = "apinotes", response = String.class)
@ResponseBody
public String uploadbatch(HttpServletRequest request) {
	// 获取请求的所有参数
	JSONObject params = getParams(request);
}

/**
 * 获取HTTP请求的参数
 */
public static JSONObject getParams(HttpServletRequest request){
	JSONObject jsonObject = new JSONObject();
	Enumeration<String> params = request.getParameterNames();
	for (Enumeration<String> e = params; e.hasMoreElements();) {
		String key = e.nextElement().toString();
		jsonObject.put(key, request.getParameter(key));
	}
	return jsonObject;
}

2> 获取上传的文件

@RequestMapping(value = "/api", method = RequestMethod.POST)
@ApiOperation(value = "apivalue", notes = "apinotes", response = String.class)
@ResponseBody
public String uploadbatch(HttpServletRequest request) {
	// 获取请求的所有文件
	List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
	for (int i = 0; i < files.size(); ++i) {
		// 获取的单个文件,并进行写入到本地操作
		writeHttpFile(files.get(i), "app/filepath/", "新的文件名称[不含文件后缀]")
	}
}

/**
 * 将HTTP接收到的文件写入到文件夹
 */
public static String writeHttpFile(MultipartFile file,String filePath,String fileName){
	BufferedOutputStream stream = null;
	String newName = "";
	if (!file.isEmpty()) {
		try {
			mkdir(filePath);
			// 拼接要保存的文件: 新的文件名+原文件的后缀名
			newName = fileName + "." + getExtensionName(file.getOriginalFilename());
			log.info("创建文件:{}--->{}.",file.getOriginalFilename(),filePath + File.separator + newName);
			byte[] bytes = file.getBytes();
			stream = new BufferedOutputStream(new FileOutputStream(new File(filePath + newName)));
			stream.write(bytes);
			stream.close();
		} catch (Exception e) {
			stream = null;
			log.error("error:{}.",e.getMessage());
		}
	}
	// 返回保存到本地的文件名
	return newName;
}

/**
 * 创建文件夹
 */
public static void mkdir(String filePath){
	File path = new File(filePath);
	if(!path.exists()){
		path.mkdirs();
	}
}

/**
 * 获取文件的后缀名
 */
public static String getExtensionName(String filename) { 
       if ((filename != null) && (filename.length() > 0)) { 
           int dot = filename.lastIndexOf('.'); 
           if ((dot >-1) && (dot < (filename.length() - 1))) { 
               return filename.substring(dot + 1); 
           } 
       } 
       return filename; 
} 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小安灬

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值