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

spring的圖片上傳

發布時間: 2023-01-14 19:25:47

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

Ⅱ 用spring怎麼把圖片上傳到前台輪播圖展示

  1. 一個文件夾用於存放圖片

  2. 一張表用於存放圖片url

  3. 一個頁面用於上傳圖片

  4. 一個頁面用於顯示slider,slider的元素使用<c:foreach>標簽來循環表裡取出的url,並顯示圖片

希望可以幫到你

Ⅲ 關於SpringBoot上傳圖片的幾種方式

1. 直接上傳到指定的伺服器路徑;
2. 上傳到第三方內容存儲器,這里介紹將圖片保存到七牛雲
3. 自己搭建文件存儲伺服器,如:FastDFS,FTP伺服器等

Ⅳ Springmvc的幾種多附件上傳方式

1.單文件上傳

1.1、頁面

文件上傳需要將表單的提交方法設置為post,將enctype的值設置為」multipart/form-data」。

<form action="${pageContext.request.contextPath}/test/upload.do" method="post" enctype="multipart/form-data">
<input type="file" name="img"><br />
<input type="submit" name="提交">
</form>
1.2 控制器
@Controller
@RequestMapping("/test")
public class MyController {

@RequestMapping(value = "/upload.do", method = RequestMethod.POST)
// 這里的MultipartFile對象變數名跟表單中的file類型的input標簽的name相同,
//所以框架會自動用MultipartFile對象來接收上傳過來的文件,
//當然也可以使用@RequestParam("img")指定其對應的參數名稱
public String upload(MultipartFile img, HttpSession session)
throws Exception {
// 如果沒有文件上傳,MultipartFile也不會為null,可以通過調用getSize()方法獲取文件的大小來判斷是否有上傳文件
if (img.getSize() > 0) {
// 得到項目在伺服器的真實根路徑,如:/home/tomcat/webapp/項目名/images
String path = session.getServletContext().getRealPath("images");
// 得到文件的原始名稱,如:美女.png
String fileName = img.getOriginalFilename();
// 通過文件的原始名稱,可以對上傳文件類型做限制,如:只能上傳jpg和png的圖片文件
if (fileName.endsWith("jpg") || fileName.endsWith("png")) {
File file = new File(path, fileName);
img.transferTo(file);
return "/success.jsp";
}
}
return "/error.jsp";
}
}
1.3springmvc.xml配置
<!-- 注意:CommonsMultipartResolver的id是固定不變的,一定是multipartResolver,不可修改 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 如果上傳後出現文件名中文亂碼可以使用該屬性解決 -->
<property name="defaultEncoding" value="utf-8"/>
<!-- 單位是位元組,不設置默認不限制總的上傳文件大小,這里設置總的上傳文件大小不超過1M(1*1024*1024) -->
<property name="maxUploadSize" value="1048576"/>
<!-- 跟maxUploadSize差不多,不過maxUploadSizePerFile是限制每個上傳文件的大小,而maxUploadSize是限制總的上傳文件大小 -->
<property name="maxUploadSizePerFile" value="1048576"/>
</bean>
2.多文件上傳

2.1頁面
<form action="${pageContext.request.contextPath}/test/upload.do" method="post" enctype="multipart/form-data">
file 1 : <input type="file" name="imgs"><br />
file 2 : <input type="file" name="imgs"><br />
file 3 : <input type="file" name="imgs"><br />
<input type="submit" name="提交">
</form>
2.2控制器
@Controller
@RequestMapping("/test")
public class MyController {

@RequestMapping(value = "/upload.do", method = RequestMethod.POST)
// 這里的MultipartFile[] imgs表示前端頁面上傳過來的多個文件,imgs對應頁面中多個file類型的input標簽的name,
// 但框架只會將一個文件封裝進一個MultipartFile對象,
// 並不會將多個文件封裝進一個MultipartFile[]數組,直接使用會報[Lorg.springframework.web.multipart.MultipartFile;.<init>()錯誤,
// 所以需要用@RequestParam校正參數(參數名與MultipartFile對象名一致),當然也可以這么寫:@RequestParam("imgs") MultipartFile[] files。
public String upload(@RequestParam MultipartFile[] imgs, HttpSession session)
throws Exception {
for (MultipartFile img : imgs) {
if (img.getSize() > 0) {
String path = session.getServletContext().getRealPath("images");
String fileName = img.getOriginalFilename();
if (fileName.endsWith("jpg") || fileName.endsWith("png")) {
File file = new File(path, fileName);
img.transferTo(file);
}
}
}
return "/success.jsp";
}
}
2.3springmvc.xml配置
<!-- 注意:CommonsMultipartResolver的id是固定不變的,一定是multipartResolver,不可修改 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 如果上傳後出現文件名中文亂碼可以使用該屬性解決 -->
<property name="defaultEncoding" value="utf-8"/>
<!-- 單位是位元組,不設置默認不限制總的上傳文件大小,這里設置總的上傳文件大小不超過1M(1*1024*1024) -->
<property name="maxUploadSize" value="1048576"/>
<!-- 跟maxUploadSize差不多,不過maxUploadSizePerFile是限制每個上傳文件的大小,而maxUploadSize是限制總的上傳文件大小 -->
<property name="maxUploadSizePerFile" value="1048576"/>
</bean>

擴展:
/*
* 通過流的方式上傳文件
* @RequestParam("file") 將name=file控制項得到的文件封裝成CommonsMultipartFile 對象
*/

/*
* 採用file.Transto 來保存上傳的文件
*/

/*
*採用spring提供的上傳文件的方法
*/

Ⅳ 如何在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",

熱點內容
英國伺服器租用地址 發布:2025-09-07 17:13:54 瀏覽:807
shadowsocks伺服器ip 發布:2025-09-07 16:58:25 瀏覽:697
財務軟體php 發布:2025-09-07 16:46:13 瀏覽:112
旅行箱密碼忘記怎麼辦 發布:2025-09-07 16:27:19 瀏覽:290
sql列合並查詢 發布:2025-09-07 16:25:48 瀏覽:143
mysql網站資料庫 發布:2025-09-07 16:20:45 瀏覽:323
換行Linux 發布:2025-09-07 16:20:43 瀏覽:154
如何遷移rtx到另一台伺服器 發布:2025-09-07 16:14:20 瀏覽:420
訪問學生簽證 發布:2025-09-07 16:14:11 瀏覽:731
安卓手機怎麼使用俄語輸入法 發布:2025-09-07 15:56:13 瀏覽:796