java后台接受到图片后保存方法

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

java后台接受到图片后保存方法

  2021-04-03 我要评论

Java是一门面向对象编程语言,不仅吸收了C++语言的各种优点,还摒弃了C++里难以理解的多继承、指针等概念,因此Java语言具有功能强大和简单易用两个特征。Java语言作为静态面向对象编程语言的代表,极好地实现了面向对象理论,允许程序员以优雅的思维方式进行复杂的编程  。

Java具有简单性、面向对象、分布式、健壮性、安全性、平台独立与可移植性、多线程、动态性等特点 。Java可以编写桌面应用程序、Web应用程序、分布式系统和嵌入式系统应用程序等 。

  • 第一步:借助于springmvc框架的平台实现。
  • 第二步:java网页下载功能怎么获取文件名。
  • 第三步:前端如何实现突破预览效果。

第二步骤:主要功能实现。springboot默认是集成springmvc,使用springboot和直接使用springmvc上传是一样的。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>

 

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

测试。

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

您可能感兴趣的文章:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们