java-http接口-文件上传

java

  最近有一个需求,需要对接附件,直接以文件的形式传输,接口为http接口,代码如下:

    @RequestMapping(value = "/upLoadFuJian", method = RequestMethod.POST)

@ResponseBody

public Map<String, Object> upLoadFuJian(@RequestParam MultipartFile file,HttpServletRequest request) throws IllegalStateException, IOException{

Map<String, Object> map = new HashMap<String, Object>();

// 判断文件是否为空

if (!file.isEmpty()) {

try {

//判断文件目录是否存在,否则自动生成

File directory = new File(UPLOAD_DIRECTORY);

if (!directory.exists()){

directory.mkdirs();

}

//失败跳转视图

if (file.getSize() > 30000)

map.put("message", file.getOriginalFilename()+"超过了指定大小");

// 文件保存路径

String filePath = FilenameUtils.concat(UPLOAD_DIRECTORY, file.getOriginalFilename());

// 转存文件

file.transferTo(new File(filePath));

//保存信息入库

String id = UUID.randomUUID().toString();

String newFileNameNotExt = UUID.randomUUID().toString();

String originalFileName = file.getOriginalFilename();

String newFileName = newFileNameNotExt + "." + FileUtils.getExtensionName(originalFileName);

CommonFile cf = new CommonFile();

cf.setOwnerGuid(id);

cf.setId(newFileNameNotExt);

cf.setOriginalFileName(originalFileName);

cf.setNewFileName(newFileName);

cf.setFileType(file.getContentType());

cf.setFileSize(file.getSize());

cf.setUploadFileTypeCode("kongZhiCenter");

cf.setCreateTime(System.currentTimeMillis());

cf.setIsDelete(0);

TestUtils.systemOutPrintln("cf.getFileType()=" + cf.getFileType());

commonFileService.add(cf);

map.put("message", "请求成功");

map.put("code", "200");

map.put("id", id);

} catch (Exception e) {

map.put("message", "请求失败");

map.put("code", "201");

e.printStackTrace();

}

}

return map;

}

 

以上是 java-http接口-文件上传 的全部内容, 来源链接: utcz.com/z/391299.html

回到顶部