linux webapps 目录,MultipartFile 图片上传到Linux服务器Tomcat下的webapps目录

第一次接触 linux 服务器,做图片上传的时候遇到了些坑,搞了些天总算成功了,记录一下

/**

* 上传图片

*

* @param request

* @param file

* @return

*/

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

@ResponseBody

public String uploadImg1(HttpServletRequest request, MultipartFile file) {

Gson gson = new Gson();

List pathList = new ArrayList();

String pic_path;

if (null != file) {

// 文件原名称

String myFileName = file.getOriginalFilename();

String fileName = UUID.randomUUID().toString() + "." + myFileName.

substring(myFileName.lastIndexOf(".") + 1);

try {

String tomcat_path = System.getProperty("user.dir");

//获取tomcat中项目同级路径

String bin_path = tomcat_path.substring(tomcat_path.lastIndexOf("/") + 1, tomcat_path.length());

if (("bin").equals(bin_path)) {

pic_path = tomcat_path.substring(0, System.getProperty("user.dir").lastIndexOf("/")) + "/webapps" + "/upload" + "/uploadImg/";

} else {

pic_path = tomcat_path + "/webapps" + "/upload" + "/uploadImg/";

}

logger.info("上传图片的路径:" + pic_path + fileName);

File fileDir = new File(pic_path + fileName);

//如果不存在 则创建

if (!fileDir.exists()) {

fileDir.mkdirs();

}

// 将内存中的数据写入磁盘

file.transferTo(fileDir);

//图片路径 ip:端口/upload/uploadImg/图片名

pathList.add(ImgConstant.ACCESS_IMAGE_URL + fileName);

return gson.toJson(pathList);

} catch (IllegalStateException e) {

logger.error("图片上传错误", e);

} catch (IOException e) {

logger.error("图片上传错误", e);

}

} else {

System.out.println("上传内容为空!");

}

return gson.toJson(pathList);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值