當前位置:首頁 » 文件管理 » mvc附件上傳

mvc附件上傳

發布時間: 2022-11-25 20:49:56

『壹』 求SpringMVC大文件上傳詳解及實例代碼

SpringMVC的文件上傳非常簡便,首先導入文件上傳依賴的jar:
<!-- 文件上傳所依賴的jar包 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>

在springMVC-servlet.xml配置文件中配置文件解析器:
<!--1*1024*1024即1M resolveLazily屬性啟用是為了推遲文件解析,以便捕獲文件大小異常 -->
<!--文件上傳解析器-->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="1048576"/>
<property name="defaultEncoding" value="UTF-8"/>
<property name="resolveLazily" value="true"/>
</bean>
注意解析器的id必須等於multipartResolver,否則上傳會出現異常
import org.apache.commons.io.FileUtils;
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;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;

@Controller
public class FileController {
/**
* 上傳單個文件操作
* MultipartFile file就是上傳的文件
* @return
*/
@RequestMapping(value = "/upload1.html")
public String fileUpload1(@RequestParam("file") MultipartFile file) {
try {
//將上傳的文件存在E:/upload/下
FileUtils.InputStreamToFile(file.getInputStream(), new File("E:/upload/",
file.getOriginalFilename()));
} catch (Exception e) {
e.printStackTrace();
}
//上傳成功返回原來頁面
return "/file.jsp";
}}

上傳文件時,Controller的方法中參數類型是MultipartFile即可將文件映射到參數上。
頁面:
file.jsp:
<form method="post" action="/upload1.html" enctype="multipart/form-data">
<input type="file" name="file"/>
<button type="submit" >提交</button>
</form>

『貳』 springmvc怎麼上傳文件

spring mvc(註解)上傳文件的簡單例子,這有幾個需要注意的地方
1.form的enctype=」multipart/form-data」 這個是上傳文件必須的
2.applicationContext.xml中 <bean id=」multipartResolver」 class=」org.springframework.web.multipart.commons.CommonsMultipartResolver」/> 關於文件上傳的配置不能少

大家可以看具體代碼如下:

web.xml
[html] view plain
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>webtest</display-name>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/config/applicationContext.xml
/WEB-INF/config/codeifAction.xml
</param-value>
</context-param>

<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/codeifAction.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- 攔截所有以do結尾的請求 -->
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

<welcome-file-list>
<welcome-file>index.do</welcome-file>
</welcome-file-list>
</web-app>

applicationContext.xml
[html] view plain
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"
default-lazy-init="true">

<!-- 啟動Spring MVC的註解功能,完成請求和註解POJO的映射 -->
<bean class="org.springframework.web.servlet.mvc.annotation." lazy-init="false" />

<!-- 另外最好還要加入,不然會被 XML或其它的映射覆蓋! -->
<bean class="org.springframework.web.servlet.mvc.annotation." />

<!-- 對模型視圖名稱的解析,即在模型視圖名稱添加前後綴 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />

<!-- 支持上傳文件 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>

</beans>

codeifAction.xml
[html] view plain
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"
default-lazy-init="true">

<bean id="uploadAction" class="com.codeif.action.UploadAction" />

</beans>

UploadAction.java
[java] view plain
package com.codeif.action;

import java.io.File;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class UploadAction {

@RequestMapping(value = "/upload.do")
public String upload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, ModelMap model) {

System.out.println("開始");
String path = request.getSession().getServletContext().getRealPath("upload");
String fileName = file.getOriginalFilename();
// String fileName = new Date().getTime()+".jpg";
System.out.println(path);
File targetFile = new File(path, fileName);
if(!targetFile.exists()){
targetFile.mkdirs();
}

//保存
try {
file.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
model.addAttribute("fileUrl", request.getContextPath()+"/upload/"+fileName);

return "result";
}

}

index.jsp
[html] view plain
<%@ page pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>上傳圖片</title>
</head>
<body>
<form action="upload.do" method="post" enctype="multipart/form-data">
<input type="file" name="file" /> <input type="submit" value="Submit" /></form>
</body>
</html>

WEB-INF/jsp/下的result.jsp
[html] view plain
<%@ page pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>上傳結果</title>
</head>
<body>
<img alt="" src="${fileUrl }" />
</body>
</html>

『叄』 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>

『肆』 ASP.NET mvc上傳多個附件

asp.net默認上限40960K 90秒請求就超時。你是不是傳多了

『伍』 如何使用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;
}
}

『陸』 mvc視圖中怎麼上傳圖片並顯示

如果只是上傳的話那太容易了,如果還要顯示那就難了,因為要顯示的話就不能只向伺服器提交一次請求,必須非同步提交。下面的例子是我親自寫的,非同步提交上傳圖片並預覽。全部代碼都在。

返回到前台頁面的JSON格式對象是以類的對象。
publicclassReturnImage
{
publicstringbig{get;set;}
publicstringsmall{get;set;}
publicstringisSuccessfull{get;set;}
publicstringmessage{get;set;}
}

對於上傳和生成縮略圖,請自行完成,以下是ASP.NETMVC的例子。
publicclassHomeController:Controller
{
//
//GET:/Home/
publicActionResultIndex()
{
returnView();
}
///<summary>
///上傳圖片
///</summary>
///<returns></returns>
publicActionResultUploadImage()
{
//定義錯誤消息
JsonResultmsg=newJsonResult();
try
{
//接受上傳文件
HttpPostedFileBasepostFile=Request.Files["upImage"];
if(postFile!=null)
{
DateTimetime=DateTime.Now;
//獲取上傳目錄轉換為物理路徑
stringuploadPath=Server.MapPath("~/UploadFiles/"+time.Year+"/"+time.ToString("yyyyMMdd")+"/");
//文件名
stringfileName=time.ToString("yyyyMMddHHmmssfff");
//後綴名稱
stringfiletrype=System.IO.Path.GetExtension(postFile.FileName);
//獲取文件大小
longcontentLength=postFile.ContentLength;
//文件不能大於2M
if(contentLength<=1024*2048)
{
//如果不存在path目錄
if(!Directory.Exists(uploadPath))
{
//那麼就創建它
Directory.CreateDirectory(uploadPath);
}
//保存文件的物理路徑
stringsaveFile=uploadPath+fileName+"_big"+filetrype;
try
{
//保存文件
postFile.SaveAs(saveFile);
//保存縮略圖的物理路徑
stringsmall=uploadPath+fileName+"_small"+filetrype;
MakeThumbnail(saveFile,small,320,240,"W");
ReturnImageimage=newReturnImage();
image.big="/UploadFiles/"+time.Year+"/"+time.ToString("yyyyMMdd")+"/"+fileName+"_big"+filetrype;
image.small="/UploadFiles/"+time.Year+"/"+time.ToString("yyyyMMdd")+"/"+fileName+"_small"+filetrype;
msg=Json(image);
}
catch
{
msg=Json("上傳失敗");
}
}
else
{
msg=Json("文件大小超過限制要求");
}
}
else
{
msg=Json("請選擇文件");
}
}
catch(Exceptione)
{
;
}
msg.ContentType="text/html";
returnmsg;
}
///<summary>

由於回答超過最大限制,///生成縮略圖的代碼請向我索取

『柒』 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

『捌』 ASP.NET MVC 上傳多個附件Controller 獲取不到值

在方法上加個斷點 用fiddler ff 或者是chrome 去監視你的上傳執行的get 或者post請求看有沒有東西如果有而且後台中斷變數監視里也有值~檢查你後台代碼。如果反之檢查前面的js。話說你Request.Files["UploadFile"]只有一個參數一個文件流也太簡單了。前台請求的時候多傳幾個參數來個時間戳 隨機數什麼的。只是Request.Files["UploadFile"]為空也不一定好區分你前台的代碼有沒有問題

『玖』 .net MVC中 在視圖中上傳的附件圖片怎麼保存到資料庫

圖片保存到資料庫不是最佳的選擇.

你可以搜索一下Uploadify 插件. 這個插件非常好用
一般將圖片存為圖片文件.

大致代碼如下:

$("#btn_upload_attachment").uploadify({
height: 25,
swf: '../Scripts/plugin/uplodify/uploadify.swf',
uploader: '/Home/Upload',
queueSizeLimit: 1,
formData: { ID: newId },
buttonText: '選擇文件',
width: 80,
onUploadSuccess: function (file, data, response) {
eval("data=" + data);
AddToAttachmentList(data.Data);
}
});

後台代碼處理:
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult Upload(HttpPostedFileBase fileData, Guid? ID)
{
if (fileData != null)
{
try
{
// 文件上傳後的保存路徑
var filePath = Path.Combine(ConfigurationManager.AppSettings["BusinessFiles"], Ticket.OrgId.ToString());
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
var fileName = Path.GetFileName(fileData.FileName);// 原始文件名稱
var fileExtension = Path.GetExtension(fileName); // 文件擴展名
var fileID = Guid.NewGuid();
var saveName = fileID.ToString() + fileExtension; // 保存文件名稱

fileData.SaveAs(filePath + "/" + saveName);
// 作為臨時附件存入附件表
var attachments = new Attachments();
attachments.ID = fileID;
attachments.OrgID = Ticket.OrgId;
attachments.BusinessType = (byte)BusinessType.TransferContract;
attachments.Status = (byte)AttachmentStatus.Temp;
if (ID.HasValue)
{
attachments.BusinessID = ID.Value;
}
attachments.Extension = fileExtension;
attachments.Name = fileName;
attachments.Size = fileData.ContentLength;
attachments.UploadTime = GetNow();
attachments.UploadBy = Ticket.EmployeeName;
attachments.UploadByID = Ticket.UserId;
AttachmentsBLL.SaveAttachment(attachments);
return Json(new { Success = true, FileName = fileName, SaveName = saveName, FileID = fileID, Data = attachments });
}
catch (Exception ex)
{
return Json(new { Success = false, Message = ex.Message }, JsonRequestBehavior.AllowGet);
}
}
else
{
return Json(new { Success = false, Message = "請選擇要上傳的文件!" }, JsonRequestBehavior.AllowGet);
}
}

熱點內容
c可以用來編譯系統軟體嗎 發布:2024-10-05 16:22:26 瀏覽:17
U盤和存儲器 發布:2024-10-05 16:22:04 瀏覽:896
cmdc語言 發布:2024-10-05 15:58:32 瀏覽:550
伺服器怎麼弄公網ip 發布:2024-10-05 15:57:02 瀏覽:640
設備配置在什麼地方 發布:2024-10-05 15:44:59 瀏覽:249
matlab外部介面編程 發布:2024-10-05 15:36:58 瀏覽:365
C事件編程 發布:2024-10-05 15:15:43 瀏覽:639
一台伺服器出現兩IP 發布:2024-10-05 15:10:05 瀏覽:925
md5加密演算法c 發布:2024-10-05 15:05:40 瀏覽:761
如何重設控制器密碼 發布:2024-10-05 14:19:13 瀏覽:440