您好,登錄后才能下訂單哦!
這篇文章主要為大家展示了“SpringMVC如何實(shí)現(xiàn)多個(gè)文件上傳及上傳后立即顯示圖片功能”,內(nèi)容簡(jiǎn)而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“SpringMVC如何實(shí)現(xiàn)多個(gè)文件上傳及上傳后立即顯示圖片功能”這篇文章吧。
多文件上傳就是改良一個(gè)方法把MultipartFile類(lèi)換成CommonsMultipartFile類(lèi),因?yàn)樯蟼鞫鄠€(gè)文件用數(shù)組方式的話MultipartFile類(lèi)不能初始化,它不支持?jǐn)?shù)組
package com.meng.upload; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.commons.CommonsMultipartFile; @Controller public class upload { @RequestMapping(value="/upload",method=RequestMethod.POST) public String upload(@RequestParam("file1") CommonsMultipartFile[] file1, HttpServletRequest request) { for (CommonsMultipartFile commonsMultipartFile : file1) { try { File file = new File(request.getServletContext().getRealPath("upload"), System.currentTimeMillis() + "_" + commonsMultipartFile.getOriginalFilename()); System.out.println(file.getPath()+""); FileOutputStream fileOutputStream = new FileOutputStream(file); fileOutputStream.write(commonsMultipartFile.getBytes()); fileOutputStream.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } return "ok"; } }
index.jsp頁(yè)面上傳立即顯示圖片
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <html> <head> <title>My JSP 'index.jsp' starting page</title> <script type="text/javascript"> //判斷瀏覽器是否支持FileReader接口 if (typeof FileReader == 'undefined') { alert("<h2>當(dāng)前瀏覽器不支持FileReader接口</h2>"); } //選擇圖片,馬上預(yù)覽 function xmTanUploadImg(obj) { var file = obj.files[0]; var reader = new FileReader(); reader.onload = function(e) { var img = document.getElementById("img1"); img.src = e.target.result; } reader.readAsDataURL(file); } </script> </head> <body> <form action="upload.upload" method="post" enctype="multipart/form-data"> file1::<input type="file" name="file1" accept=".jpg,.png" onchange="xmTanUploadImg(this)" /> <input type="submit" /> <img id="img1" /> </form> </body> </html>
以上是“SpringMVC如何實(shí)現(xiàn)多個(gè)文件上傳及上傳后立即顯示圖片功能”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。