java后台接受到图片后怎么保存

2025-10-10 09:43:45

1、第一步:借助于springmvc框架的平台实现。

1、参考:Ajax上传文件并显示进度条

1.1 前台根据原生的js实现异步上传功能。

2、springboot实现图片上传主要也是借助于springboot+表单实现上传的功能

2、第二步:java网页下载功能怎么获取文件名。

下载可以参考:单独介绍下载一般要如何操作

3、第三步:前端如何实现突破预览效果。

1、参考经验:js如何显示图片

1、springboot默认是集成springmvc,使用springboot和直接使用springmvc上传是一样的。

2、前端代码:

1、具体代码如下所示:

此处直接使用的表单同步提交。

<!DOCTYPE html>

<html>

<head>

<title>图片上传</title>

<meta name="keywords" content="keyword1,keyword2,keyword3"></meta>

<meta name="description" content="this is my page"></meta>

<meta name="content-type" content="text/html; charset=UTF-8"></meta>

</head>

<body>

<form enctype="multipart/form-data" method="post" action="/testUploadimg"> 

图片:<input type="file" name="file" /><br/> 

<input type="submit" value="上传" />.

</form>

</body>

</html>

java后台接受到图片后怎么保存

3、控制器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格式化到毫秒也可以解决文件重名的问题。

java后台接受到图片后怎么保存

4、测试。

打开页面地址如下图所示:

java后台接受到图片后怎么保存

java后台接受到图片后怎么保存

java后台接受到图片后怎么保存

java后台接受到图片后怎么保存

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢