java保存图片进度条_java后台接受到图片后怎么保存

控制器UploadController 实现

UploadController 主要分为3部分

1.1 调整页面请求goUploadImg

1.2 上传请求方法uploadImg

1.3 存储图片方法uploadFile

@Controllerpublic class UploadController {

//跳转到上传文件的页面

@RequestMapping(value = "/gouploadimg", method = RequestMethod.GET)

public String goUploadImg() {

//跳转到 templates 目录下的 uploadimg.html

return "uploadimg";

}

//处理文件上传

@ResponseBody //返回json数据

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

public String uploadImg(@RequestParam("file") MultipartFile file,

HttpServletRequest request) {

tring contentType = file.getContentType();

String fileName = file.getOriginalFilename();

String filePath = "D:/img";

if (file.isEmpty()) {

return "文件为空!";

}

try {

uploadFile(file.getBytes(), filePath, fileName);

} catch (Exception e) {

// TODO: handle exception

}

//返回json

return "上传成功";

}

public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {

File targetFile = new File(filePath);

if (!targetFile.exists()) {

targetFile.mkdirs();

}

FileOutputStream out = new FileOutputStream(filePath +"/"+ fileName);

out.write(file);

out.flush();

out.close();

}

}

2:同时需要将上传图片的原始文件名和存储文件名、以及关联id存入一个数据表中。

2.1 将存储文件名设置为UUID,避免存储文件名重复

public static String getUUID(){

UUID uuid=UUID.randomUUID();

String str = uuid.toString();

String uuidStr=str.replace("-", "");

return uuidStr;

}

2.2 将存储文件名按照时间生成,避免存储文件名重复

System.nanoTime()

该函数是返回纳秒的。1毫秒=1纳秒*1000*1000

如:long time1=System.nanoTime();

2.3 或者借助于SimpleDateFormat 将Date格式化到毫秒也可以解决文件重名的问题。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值