java后臺接受到圖片后保存方法
Java是一門面向對象編程語言,不僅吸收了C++語言的各種優(yōu)點,還摒棄了C++里難以理解的多繼承、指針等概念,因此Java語言具有功能強大和簡單易用兩個特征。Java語言作為靜態(tài)面向對象編程語言的代表,極好地實現了面向對象理論,允許程序員以優(yōu)雅的思維方式進行復雜的編程 。
Java具有簡單性、面向對象、分布式、健壯性、安全性、平臺獨立與可移植性、多線程、動態(tài)性等特點 。Java可以編寫桌面應用程序、Web應用程序、分布式系統(tǒng)和嵌入式系統(tǒng)應用程序等 。
- 第一步:借助于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:同時需要將上傳圖片的原始文件名和存儲文件名、以及關聯(lián)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 Socket使用加密協(xié)議進行傳輸對象的方法
這篇文章主要介紹了Java Socket使用加密協(xié)議進行傳輸對象的方法,結合實例形式分析了java socket加密協(xié)議相關接口與類的調用方法,以及服務器、客戶端實現技巧,需要的朋友可以參考下2017-06-06
spring?boot獲取session的值為null問題及解決方法
我在登陸的時候,登陸成功后將name存進了session,然后在獲取個人信息時取出session里的name的值為null,接下來通過本文給大家分享springboot獲取session的值為null問題,需要的朋友可以參考下2023-05-05
詳解Spring cloud使用Ribbon進行Restful請求
這篇文章主要介紹了詳解Spring cloud使用Ribbon進行Restful請求,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-04-04

