springmvc上傳下載
A. SpringMVC使用commons fileupload 上傳文件,parseRequest(request)得到的集合為空,急等大神指點。
既然你已經用了Spring MVC,就沒有必要自己寫上傳的代碼了,這樣做
下一個這樣的方法,把MultipartFile傳進去
public String upload(@RequestParam(value = "image") MultipartFile image)
然後就可以這樣做了
image.transferTo(new File("想要保存到哪裡"));
image還有其他的方法,自己看一下就可以了
XML配置一個bean
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="104857600" />
<property name="maxInMemorySize" value="4096" />
<property name="defaultEncoding" value="utf-8" />
</bean>
B. spring mvc word文件上傳之後可預覽的實現方法或者步驟
你好!
springmvc文件上傳
1.加入jar包:
commons-fileupload-1.2.2.jar
commons-io-2.0.1.jar
lperson.java中加屬性,實現get ,set方法
private String photoPath;
2.創建WebRoot/upload目錄,存放上傳的文件
1 <sf:form id="p" action="saveOrUpdate"
2 method="post"
3 modelAttribute="person"
4 enctype="multipart/form-data">
5
6 <sf:hidden path="id"/>
7 name: <sf:input path="name"/><br>
8 age: <sf:input path="age"/><br>
9 photo: <input type="file" name="photo"/><br>
上面第9行文件上傳框,不能和實體對象屬性同名,類型不同
controller配置
1 12、文件上傳功能實現 配置文件上傳解析器
2 @RequestMapping(value={"/saveOrUpdate"},method=RequestMethod.POST)
3 public String saveOrUpdate(Person p,
4 @RequestParam("photo") MultipartFile file,
5 HttpServletRequest request
6 ) throws IOException{
7 if(!file.isEmpty()){
8 ServletContext sc = request.getSession().getServletContext();
9 String dir = sc.getRealPath(「/upload」); //設定文件保存的目錄
10
11 String filename = file.getOriginalFilename(); //得到上傳時的文件名
12 FileUtils.writeByteArrayToFile(new File(dir,filename), file.getBytes());
13
14 p.setPhotoPath(「/upload/」+filename); //設置圖片所在路徑
15
16 System.out.println("upload over. "+ filename);
17 }
18 ps.saveOrUpdate(p);
19 return "redirect:/person/list.action"; //重定向
20 }
3.文件上傳功能實現 spring-mvc.xml 配置文件上傳解析器
1 <!-- 文件上傳解析器 id 必須為multipartResolver -->
2 <bean id="multipartResolver"
3 class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
4 <property name="maxUploadSize" value=「10485760"/>
5 </bean>
6
7 maxUploadSize以位元組為單位:10485760 =10M id名稱必須這樣寫
1 映射資源目錄
2 <mvc:resources location="/upload/" mapping="/upload/**"/>
隨即文件名常用的三種方式:
文件上傳功能(增強:防止文件重名覆蓋)
fileName = UUID.randomUUID().toString() + extName;
fileName = System.nanoTime() + extName;
fileName = System.currentTimeMillis() + extName;
1 if(!file.isEmpty()){
2 ServletContext sc = request.getSession().getServletContext();
3 String dir = sc.getRealPath("/upload");
4 String filename = file.getOriginalFilename();
5
6
7 long _lTime = System.nanoTime();
8 String _ext = filename.substring(filename.lastIndexOf("."));
9 filename = _lTime + _ext;
10
11 FileUtils.writeByteArrayToFile(new File(dir,filename), file.getBytes());
12
13 p.setPhotoPath("/upload/"+filename);
14
15 System.out.println("upload over. "+ filename);
16 }
圖片顯示 personList.jsp
1 <td><img src="${pageContext.request.contextPath}${p.photoPath}">${p.photoPath}</td>
C. 如何在spring mvc中上傳圖片並顯示出來
可以使用組件上傳JspSmartUpload.這是一個類.
<form name="f1" id="f1" action="/demo/servlet/UploadServlet" method="post" enctype="multipart/form-data">
<table border="0">
<tr>
<td>用戶名:</td>
<td><input type="text" name="username" id="username"></td>
</tr>
<tr>
<td>密碼:</td>
<td><input type="password" name="password" id="password"></td>
</tr>
<tr>
<td>相片:</td>
<td><input type="file" name="pic" id="pic"></td>
</tr>
<tr>
<td>相片:</td>
<td><input type="file" name="pic2" id="pic2"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit"></td>
</tr>
</table>
</form>
這里直接通過表單提交給servlet訪問,spring中的話需要配置(一般就不用servlet了,自行配置).
以上在JSp頁面中,以下是servlet/action中的代碼,由於採用了spring框架,怎麼做你知道的(沒有servlet但是有action).
package com.demo.servlet;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jspsmart.upload.File;
import com.jspsmart.upload.Files;
import com.jspsmart.upload.Request;
import com.jspsmart.upload.SmartUpload;
public class UploadServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
SmartUpload su = new SmartUpload();
//初始化
su.initialize(this.getServletConfig(), request, response);
try {
//限制格式
//只允許哪幾種格式
su.setAllowedFilesList("jpg,JPG,png,PNG,bmp,gif,GIF");
//不允許哪幾種格式上傳,不允許exe,bat及無擴展名的文件類型
//su.setDeniedFilesList("exe,bat,,");
//限制大小,每個上傳的文件大小都不能大於100K
su.setMaxFileSize(100*1024);
//上傳文件的總大小不能超過100K
//su.setTotalMaxFileSize(100*1024);
//上傳
su.upload();
//唯一文件名
//得到文件集合
Files files = su.getFiles();
for(int i=0;i<files.getCount();i++)
{
//獲得每一個上傳文件
File file = files.getFile(i);
//判斷客戶是否選擇了文件
if(file.isMissing())
{
continue;
}
//唯一名字
Random rand = new Random();
//String fileName = System.currentTimeMillis()+""+rand.nextInt(100000)+"."+file.getFileExt();
String fileName = UUID.randomUUID()+"."+file.getFileExt();
//以當前日期作為文件夾
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dirPath = sdf.format(new Date());
//獲得物理路徑
String realDirPath= this.getServletContext().getRealPath(dirPath);
java.io.File dirFile = new java.io.File(realDirPath);
//判斷是否存在
if(!dirFile.exists())
{
//創建文件夾
dirFile.mkdir();
}
//保存
file.saveAs("/"+dirPath+"/"+fileName);
//file.saveAs("/uploadFiles/"+fileName);
}
//原名保存
//su.save("/uploadFiles");
} catch (Exception e) {
System.out.println("格式錯誤");
}
//獲得用戶名
Request req = su.getRequest();
String username = req.getParameter("username");
System.out.println(username);
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
特別注意導的包是JspSmartUpload中的還是java.io.*中的.
再次說明,這段代碼是servlet中的,spring中的action可以剪切以上的一部分.請自行調整.
D. springmvc 怎麼將文件上傳到linux伺服器
Spring MVC為文件上傳提供了直接的支持,這種支持是通過即插即用的MultipartResolver實現的。Spring使用Jakarta Commons FileUpload 技術實現了一個MultipartResolver實現類:CommonsMultipartResolver。
Spring MVC上下文中默認沒有裝配MultipartResolver,因此默認情況下不能處理文件的上傳工作。如果想要使用Spring的文件上傳功能,需要先在上下文中配置MultipartResolver。
第一步:配置MultipartResolver
使用CommonsMultipartResolver配置一個MultipartResolver解析器:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
p:defaultEncoding="UTF-8"
p:maxUploadSize="5242880"
p:uploadTempDir="upload/temp"
/>
defaultEncoding必須和用戶JSP的pageEncoding屬性一致,以便正確讀取表單的內容。uploadTempDir是文件上傳過程所使用的臨時目錄,文件上傳完成後,臨時目錄中的臨時文件會被自動清除。
第二步:編寫文件上傳表單頁面和控制器
JSP頁面如下:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
<h1>選擇上傳文件</h1>
<form action="<%=basePath%>user/upload.do" method="post" enctype="multipart/form-data">
文件名:<input type="text" name="name" /><br/>
<input type="file" name="file" /><br/>
<input type="submit" />
</form>
</body>
</html>
注意:負責上傳的表單和一般表單有一些區別,表單的編碼類型必須是"Multipart/form-data"
控制器UserController如下:
package com.web;
import java.io.File;
import java.io.IOException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
@Controller
@RequestMapping(value = "/user")
public class UserController {
@RequestMapping(value = "/upload.do")
public String updateThumb(@RequestParam("name") String name,
@RequestParam("file") MultipartFile file)
throws IllegalStateException, IOException {
if (!file.isEmpty()) {
file.transferTo(new File("d:/temp/"
+ name
+ file.getOriginalFilename().substring(
file.getOriginalFilename().lastIndexOf("."))));
return "redirect:success.html";
} else {
return "redirect:fail.html";
}
}
}
Spring MVC會將上傳文件綁定到MultipartFile對象中。MultipartFile提供了獲取上傳文件內容、文件名等內容,通過transferTo方法還可將文件存儲到硬體中,具體說明如下:
byte[] getBytes() :獲取文件數據
String getContentType():獲取文件MIME類型,如image/pjpeg、text/plain等
InputStream getInputStream():獲取文件流
String getName():獲取表單中文件組件的名字
String getOriginalFilename():獲取上傳文件的原名
long getSize():獲取文件的位元組大小,單位為byte
boolean isEmpty():是否有上傳的文件
void transferTo(File dest):可以使用該文件將上傳文件保存到一個目標文件中
源碼:uploadtest.zip
E. 如何在spring mvc中上傳圖片並顯示出來
(1)在spring mvc的配置文件中配置:
<beanid="multipartResolver"class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<propertyname="uploadTempDir"value="/tmp"/><!--臨時目錄-->
<propertyname="maxUploadSize"value="10485760"/><!--10M-->
</bean>
(2)文件上傳表單和結果展示頁fileupload.jsp:
<%@pagelanguage="java"contentType="text/html;charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglibprefix="mvc"uri="http://www.springframework.org/tags/form"%>
<%@taglibprefix="c"uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>SpringMVC文件上傳</title>
</head>
<body>
<h2>圖片文件上傳</h2>
<mvc:formmodelAttribute="user"action="upload.html"
enctype="multipart/form-data">
<table>
<tr>
<td>用戶名:</td>
<td><mvc:inputpath="userName"/></td>
</tr>
<tr>
<td>選擇頭像:</td>
<td><inputtype="file"name="file"/></td>
</tr>
<tr>
<tdcolspan="2"><inputtype="submit"value="Submit"/></td>
</tr>
</table>
</mvc:form>
<br><br>
<c:iftest="${u!=null}">
<h2>上傳結果</h2>
<table>
<c:iftest="${u.userName!=null}">
<tr>
<td>用戶名:</td>
<td>${u.userName}</td>
</tr>
</c:if>
<c:iftest="${u.logoSrc!=null}">
<tr>
<td>頭像:</td>
<td><imgsrc="${u.logoSrc}"width="100px"height="100px"></td>
</tr>
</c:if>
</table>
</c:if>
</body>
</html>
(3)後台處理UploadController.java:
packagecn.zifangsky.controller;
importjava.io.File;
importjava.io.IOException;
importjavax.servlet.http.HttpServletRequest;
importorg.apache.commons.io.FileUtils;
importorg.springframework.stereotype.Controller;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RequestMethod;
importorg.springframework.web.bind.annotation.RequestParam;
importorg.springframework.web.multipart.MultipartFile;
importorg.springframework.web.servlet.ModelAndView;
importcn.zifangsky.model.User;
importcn.zifangsky.utils.StringUtile;
@Controller
publicclassUploadController{
@RequestMapping(value="/form")
publicModelAndViewform(){
ModelAndViewmodelAndView=newModelAndView("fileupload","user",newUser());
returnmodelAndView;
}
@RequestMapping(value="/upload",method=RequestMethod.POST)
publicModelAndViewupload(Useruser,@RequestParam("file")MultipartFiletmpFile,HttpServletRequestrequest){
ModelAndViewmodelAndView=newModelAndView("fileupload");
if(tmpFile!=null){
//獲取物理路徑
StringtargetDirectory=request.getSession().getServletContext().getRealPath("/uploads");
StringtmpFileName=tmpFile.getOriginalFilename();//上傳的文件名
intdot=tmpFileName.lastIndexOf('.');
Stringext="";//文件後綴名
if((dot>-1)&&(dot<(tmpFileName.length()-1))){
ext=tmpFileName.substring(dot+1);
}
//其他文件格式不處理
if("png".equalsIgnoreCase(ext)||"jpg".equalsIgnoreCase(ext)||"gif".equalsIgnoreCase(ext)){
//重命名上傳的文件名
StringtargetFileName=StringUtile.renameFileName(tmpFileName);
//保存的新文件
Filetarget=newFile(targetDirectory,targetFileName);
try{
//保存文件
FileUtils.InputStreamToFile(tmpFile.getInputStream(),target);
}catch(IOExceptione){
e.printStackTrace();
}
Useru=newUser();
u.setUserName(user.getUserName());
u.setLogoSrc(request.getContextPath()+"/uploads/"+targetFileName);
modelAndView.addObject("u",u);
}
returnmodelAndView;
}
returnmodelAndView;
}
}
在上面的upload方法中,為了接收上傳的文件,因此使用了一個MultipartFile類型的變數來接收上傳的臨時文件,同時為了給文件進行重命名,我調用了一個renameFileName方法,這個方法的具體內容如下:
/**
*文件重命名
*/
(StringfileName){
StringformatDate=newSimpleDateFormat("yyMMddHHmmss").format(newDate());//當前時間字元串
intrandom=newRandom().nextInt(10000);
Stringextension=fileName.substring(fileName.lastIndexOf("."));//文件後綴
returnformatDate+random+extension;
}
註:上面用到的model——User.java:
packagecn.zifangsky.model;
publicclassUser{
privateStringuserName;//用戶名
privateStringlogoSrc;//頭像地址
publicStringgetUserName(){
returnuserName;
}
publicvoidsetUserName(StringuserName){
this.userName=userName;
}
publicStringgetLogoSrc(){
returnlogoSrc;
}
publicvoidsetLogoSrc(StringlogoSrc){
this.logoSrc=logoSrc;
}
}
至此全部結束
效果如下:
(PS:純手打,望採納)
F. spring mvc上傳文件表單同時傳值的問題
當在上傳表單中設置了 enctype="multipart/form-data" 時post傳過去的字元串的值為null,會報 HTTP Status 400 - Required String parameter 'description' is not present 錯誤。
解決方案:
1、首先在pom.xml中添加
然後在applicationContext.xml中添加即可解決,這樣的話spring會對表單的數據進行處理,就算使用了enctype="multipart/form-data"進行傳值也能拿到數據