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;
}