當前位置:首頁 » 文件管理 » springmvc上傳圖片

springmvc上傳圖片

發布時間: 2022-05-30 06:24:26

① 請教spring mvc 的文件上傳

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>

② springmvc怎麼上傳文件

SpringMVC上傳文件的三種方式
前台:

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Insert title here</title></head><body><form name="serForm" action="/SpringMVC006/fileUpload" method="post" enctype="multipart/form-data"><h1>採用流的方式上傳文件</h1><input type="file" name="file"><input type="submit" value="upload"/></form> <form name="Form2" action="/SpringMVC006/fileUpload2" method="post" enctype="multipart/form-data"><h1>採用multipart提供的file.transfer方法上傳文件</h1><input type="file" name="file"><input type="submit" value="upload"/></form> <form name="Form2" action="/SpringMVC006/springUpload" method="post" enctype="multipart/form-data"><h1>使用spring mvc提供的類的方法上傳文件</h1><input type="file" name="file"><input type="submit" value="upload"/></form></body></html>

配置:

<!-- 多部分文件上傳 --><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"></property></bean>

後台:
方式一:

/* * 通過流的方式上傳文件 * @RequestParam("file") 將name=file控制項得到的文件封裝成CommonsMultipartFile 對象 */ @RequestMapping("fileUpload") public String fileUpload(@RequestParam("file") CommonsMultipartFile file) throws IOException { //用來檢測程序運行時間 long startTime=System.currentTimeMillis(); System.out.println("fileName:"+file.getOriginalFilename()); try { //獲取輸出流 OutputStream os=new FileOutputStream("E:/"+new Date().getTime()+file.getOriginalFilename()); //獲取輸入流 CommonsMultipartFile 中可以直接得到文件的流 InputStream is=file.getInputStream(); int temp; //一個一個位元組的讀取並寫入 while((temp=is.read())!=(-1)) { os.write(temp); } os.flush(); os.close(); is.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } long endTime=System.currentTimeMillis(); System.out.println("方法一的運行時間:"+String.valueOf(endTime-startTime)+"ms"); return "/success"; }

方式二:

/* * 採用file.Transto 來保存上傳的文件 */ @RequestMapping("fileUpload2") public String fileUpload2(@RequestParam("file") CommonsMultipartFile file) throws IOException { long startTime=System.currentTimeMillis(); System.out.println("fileName:"+file.getOriginalFilename()); String path="E:/"+new Date().getTime()+file.getOriginalFilename(); File newFile=new File(path); //通過CommonsMultipartFile的方法直接寫文件(注意這個時候) file.transferTo(newFile); long endTime=System.currentTimeMillis(); System.out.println("方法二的運行時間:"+String.valueOf(endTime-startTime)+"ms"); return "/success"; }

方式三:

/* *採用spring提供的上傳文件的方法 */ @RequestMapping("springUpload") public String springUpload(HttpServletRequest request) throws IllegalStateException, IOException { long startTime=System.currentTimeMillis(); //將當前上下文初始化給 CommonsMutipartResolver (多部分解析器) CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver( request.getSession().getServletContext()); //檢查form中是否有enctype="multipart/form-data" if(multipartResolver.isMultipart(request)) { //將request變成多部分request MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request; //獲取multiRequest 中所有的文件名 Iterator iter=multiRequest.getFileNames(); while(iter.hasNext()) { //一次遍歷所有文件 MultipartFile file=multiRequest.getFile(iter.next().toString()); if(file!=null) { String path="E:/springUpload"+file.getOriginalFilename(); //上傳 file.transferTo(new File(path)); } } } long endTime=System.currentTimeMillis(); System.out.println("方法三的運行時間:"+String.valueOf(endTime-startTime)+"ms"); return "/success"; }

我們看看測試上傳的時間:
第一次我用一個4M的文件:
fileName:test.rar
方法一的運行時間:14712ms
fileName:test.rar
方法二的運行時間:5ms
方法三的運行時間:4ms

第二次:我用一個50M的文件
方式一進度很慢,估計得要個5分鍾
方法二的運行時間:67ms
方法三的運行時間:80ms

從測試結果我們可以看到:用springMVC自帶的上傳文件的方法要快的多!
對於測試二的結果:可能是方法三得挨個搜索,所以要慢點。不過一般情況下我們是方法三,因為他能提供給我們更多的方法

③ spring mvc 怎麼實現上傳文件

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>

④ springmvc+ajax上傳圖片的問題。傳過去的是空值.怎麼接收圖片

因為SpringMVC只有GET請求才能通過方法上加參數獲取到值,POST是不能通過這種方式獲取的,可以通過request.getParameter(key) 或者 封裝成對象(屬性對應前端參數)會自動填充。

另外我記得Ajax上傳文件不能直接用$.ajax這種方式傳,我的方法如下:
var form = new FormData();
var xhr = new XMLHttpRequest();
xhr.open("post", "url", true);

xhr.onload = function () {
alert("上傳完成!");
};
xhr.send(form);

⑤ 如何在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可以剪切以上的一部分.請自行調整.

⑥ 關於springMVC圖片上傳後的問題

你可以試一下,這個解決方法,看看能否解決,在springmvc進行文件上傳的時候,配置文件使用了multipartResolver這個bean ,這個bean的ID一定不要寫錯,檢查一下<bean id="multipartResolver",

⑦ 如何在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:純手打,望採納)

⑧ 如何使用springmvc實現文件上傳

在現在web應用的開發,springMvc使用頻率是比較廣泛的,現在給大家總結一下springMvc的上傳附件的應用,希望對大家有幫助,廢話不多說,看效果

准備jar包

4.准備上傳代碼


@Controller//spring使用註解管理bean
@RequestMapping("/upload")//向外暴露資源路徑,訪問到該類
public class UploadController {
/**
* 上傳功能
* @return
* @throws IOException
*/
@RequestMapping("/uploadFile")//向外暴露資源路徑,訪問到該方法
public String uploadFile(MultipartFile imgFile,HttpServletRequest req) throws IOException{
if(imgFile != null ){
//獲取文件輸入流
InputStream inputStream = imgFile.getInputStream();
//隨機產生文件名,原因是:避免上傳的附件覆蓋之前的附件
String randName = UUID.randomUUID().toString();//隨機文件名
//獲取文件原名
String originalFilename = imgFile.getOriginalFilename();
//獲取文件後綴名(如:jpgpng...)
String extension = FilenameUtils.getExtension(originalFilename);
//新名字
String newName = randName+"."+extension;
//獲取servletContext
ServletContext servletContext = req.getSession().getServletContext();
//獲取根路徑
String rootPath = servletContext.getRealPath("/");

File file = new File(rootPath,"upload");
//判斷文件是否存在,若不存在,則創建它
if(!file.exists()){
file.mkdirs();
}
//獲取最終輸出的位置
FileOutputStream fileOutputStream = new FileOutputStream(new File(file,newName));
//上傳附件
IOUtils.(inputStream, fileOutputStream);
}
return null;
}
}

⑨ spring+spring mvc+ hibernate框架里怎麼實現圖片的上傳,下載,展示功能

這個嘛 只和SpringMVC有點關系。 前端提交的文件,由springmvc攔截進行處理。
您可以使用上傳插件。比如網路上傳插件:Web Uploader。
怎麼用的話,官網有Demo。也有API文檔,可以自行查閱。
當然不用插件的話,也可以自己做個簡單的,用Form表單提交到後台,後台對文件進行保存,展示的話直接用<img src='xxx路徑'>。您可以自己組織語言網路搜索一下代碼怎麼寫。
上傳文件實際上就是傳輸一些數據到後台,然後使用java把這些數據保存到硬碟上,前端直接根據路徑來進行訪問。

⑩ 關於「springmvc上傳圖片file already exists and could not deleted」

上傳文件時候,要去你指定的目錄新建文件. 如果已經存在了,就會有這樣的提示. 一般做上傳,我們習慣重新命名上傳的文件.這樣可以解決你提出來的問題.

熱點內容
中國電腦伺服器的發展 發布:2024-10-18 12:31:38 瀏覽:777
ktv系統源碼 發布:2024-10-18 12:26:45 瀏覽:508
阿克蘇哪裡有開密碼箱 發布:2024-10-18 12:26:00 瀏覽:282
如何使用伺服器跑自己的軟體 發布:2024-10-18 12:22:28 瀏覽:799
電腦怎樣編程 發布:2024-10-18 12:06:55 瀏覽:528
圖的鄰接表存儲及遍歷 發布:2024-10-18 12:02:31 瀏覽:495
如何查詢電腦型號的配置 發布:2024-10-18 11:57:42 瀏覽:273
如何開張一個租賃伺服器 發布:2024-10-18 11:46:13 瀏覽:826
python解析json文件 發布:2024-10-18 11:29:34 瀏覽:311
編譯程序的生成程序 發布:2024-10-18 11:29:27 瀏覽:404