当前位置: 移动技术网 > IT编程>开发语言>Java > java后台接受到图片后保存方法

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

2019年07月19日  | 移动技术网IT编程  | 我要评论

朗乡新闻,182是联通还是移动,上海宝山区邮编

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

测试。

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网