您的位置 首页 java

JAVA实现文件上传

/**

* 上传文件的方法

*

* @param File

* @return

* @throws IO Exception

*/

@PostMapping(“/upload”)

public R<Map<String, String>> upload(@ Request Param(“file”) MultipartFile file) throws IOException {

Map<String, String> resMap = new HashMap<>();

//文件判空

if (file.isEmpty()) {

resMap.put(“Error”, “400” + “File Not exists “);

return R.ok(resMap);

}

//获取文件名称

String ori_name = file.getOriginalFilename();

//需要改变文件名称需要加上文件类型oldName.substring(ori_name.lastIndexOf(“.”)+1)

//获取当前时间戳

long time = System.currentTimeMillis();

String cur_name = time + “.” + ori_name.substring(ori_name.lastIndexOf(“.”) + 1);

String path = ordinaryPath + File.separator + cur_name;

//创建文件对象

File curr_file = new File(path);

//获取文件目录判断是否存在

if (!curr_file.getParentFile().exists()) {

//确保创建文件时目标文件夹存在

curr_file.getParentFile().mkdirs();

}

try {

//存储

file.transferTo(curr_file);

} catch (IOException e) {

e.printStackTrace();

resMap.put(“Error”, “500” + “transferTo err”);

return R.ok(resMap);

}

resMap.put(“path”, path);

resMap.put(“name”, ori_name);

return R.ok(resMap);

文章来源:智云一二三科技

文章标题:JAVA实现文件上传

文章地址:https://www.zhihuclub.com/174606.shtml

关于作者: 智云科技

热门文章

网站地图