多文件上傳就是改良一個方法把MultipartFile類換成CommonsMultipartFile類,因為上傳多個文件用數(shù)組方式的話MultipartFile類不能初始化,它不支持?jǐn)?shù)組
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
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頁面上傳立即顯示圖片
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
<%@ 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( "<h1>當(dāng)前瀏覽器不支持FileReader接口</h1>" ); } //選擇圖片,馬上預(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> |
總結(jié)
以上所述是小編給大家介紹的SpringMVC多個文件上傳及上傳后立即顯示圖片功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對服務(wù)器之家網(wǎng)站的支持!
原文鏈接:http://blog.csdn.net/william_hof/article/details/78221405