Java是一門面標的目的對象編程說話,不僅接收了C++說話的各類長處,還摒棄了C++里難以理解的多擔當、指針等概念,是以Java說話具有功能壯大和簡單易用兩個特征。Java說話作為靜態面標的目的對象編程說話的代表,極好地實現了面標的目的對象理論,許可程序員以優雅的思維體例進行復雜的編程 。
Java具有簡單性、面標的目的對象、分布式、健壯性、平安性、平臺自力與可移植性、多線程、動態性等特點 。Java可以編寫桌面應用程序、Web應用程序、分布式系統和嵌入式系統應用程序等 。
第一步:借助于springmvc框架的平臺實現。
1、參考:Ajax上傳文件并顯示進度條
1.1 前臺按照原生的js實現異步上傳功能。
2、springboot實現圖片上傳本家兒要也是借助于springboot+表單實現上傳的功能
2上傳文件并顯示進度條
1實現圖片上傳
第二步:java網頁下載功能怎么獲取文件名。
下載可以參考:零丁介紹下載一般要若何操作
2網頁下載功能怎么獲取文件名
1實現下載圖片
第三步:前端若何實現沖破預覽結果。
1、參考經驗:js若何顯示圖片
0若何顯示圖片
springboot默認是集當作springmvc,利用springboot和直接利用springmvc上傳是一樣的。
前端代碼:
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格局化到毫秒也可以解決文件重名的問題。
 測試。
打開頁面地址如下圖所示:
 
 
 
 0 篇文章
如果覺得我的文章對您有用,請隨意打賞。你的支持將鼓勵我繼續創作!