mvc上傳文件
① spring mvc上傳文件到指定的文件夾中,新手不會,
第一個參數是你的前台傳遞進來的文件。
第二個參數是request對象。
第三個參數是spring mvc 綁定數據用的對象。
根據你的代碼 你的第三個參數可以不要。
第一個參數 是前台form當中有個類似於<input type="file" name="file"/>的控制項傳遞過來的文件。
② 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>
③ .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);
            }
        }
④ asp.net mvc 怎麼在服務端和客服端分別對 上傳文件類型做檢查
1.客戶端。客戶端常用的主要通過對文件名字元串進行分析,根據其擴展名進行判斷。javascript現在好像不能直接訪問客戶端上的文件了,如果有更好的辦法,歡迎交流。
2.伺服器端。伺服器端通過分析文件的二進制流,驗證文件頭部中的信息,避免改文件名後綴惡意上傳的情況。
以上資料很多,這里也放不下,網路下就好了,共勉~
⑤ spring mvc 怎麼實現上傳文件
在springmvc配置文件中這樣配置:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 編碼設置 -->
<property name="defaultEncoding" value="utf-8"/>
<!-- 上傳文件大小 -->
<property name="maxUploadSize" value="-1"/>
<!--推遲文件解析,以便在UploadAction中捕獲文件大小異常-->
<property name="resolveLazily" value="true"/>
</bean>
頁面:
<form action="upload.action" method="post" enctype="multipart/form-data">
<input type="file" name="fileUpload" />
<input type="submit" value="上傳" />  
</form>
後台:
@Controller
public class UploadAction implements ServletContextAware {
private ServletContext context;
@RequestMapping("/upload")
public String upload(HttpServletRequest request) throws Exception{
//轉換請求為文件上傳請求
MultipartHttpServletRequest mrequest=(MultipartHttpServletRequest)request;
MultipartFile mfile=mrequest.getFile("file");
if(!mfile.isEmpty()){//判斷文件是否為空
path=context.getRealPath("/upload")+File.separator+mfile.getOriginalFilename();
File file=new File(path);
mfile.transferTo(file);//保存文件
}
return "跳轉頁面";
}}
⑥ springmvc怎麼實現多文件上傳
多文件上傳其實很簡單,和上傳其他相同的參數如checkbox一樣,表單中使用相同的名稱,然後action中將MultipartFile參數類定義為數組就可以。
接下來實現:
1、創建一個上傳多文件的表單:
在CODE上查看代碼片派生到我的代碼片
<body>
<h2>上傳多個文件 實例</h2>
<form action="filesUpload.html" method="post"
enctype="multipart/form-data">
<p>
選擇文件:<input type="file" name="files">
<p>
選擇文件:<input type="file" name="files">
<p>
選擇文件:<input type="file" name="files">
<p>
<input type="submit" value="提交">
</form>
</body>  
2、編寫處理表單的action,將原來保存文件的方法單獨寫一個方法出來方便共用:
[java] view plain 
print?在CODE上查看代碼片派生到我的代碼片
/***
* 保存文件
* @param file
* @return
*/
private boolean saveFile(MultipartFile file) {
// 判斷文件是否為空
if (!file.isEmpty()) {
try {
// 文件保存路徑
String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/"
+ file.getOriginalFilename();
// 轉存文件
file.transferTo(new File(filePath));
return true;
} catch (Exception e) {
e.printStackTrace();
}
}
return false;
}
3、編寫action:
@RequestMapping("filesUpload")
public String filesUpload(@RequestParam("files") MultipartFile[] files) {
//判斷file數組不能為空並且長度大於0
if(files!=null&&files.length>0){
//循環獲取file數組中得文件
for(int i = 0;i<files.length;i++){
MultipartFile file = files[i];
//保存文件
saveFile(file);
}
}
// 重定向
return "redirect:/list.html";
}
⑦ MVC 上傳功能的例子
這是控制器代碼,我這里判斷上傳文件的格式是「.jpg",你可以換成」.CSV「格式進行檢查:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Web;
usingSystem.Web.Mvc;
namespaceMvcTest1.Controllers
{
publicclassHomeController:Controller
{
publicActionResultIndex()
{
ViewBag.Message="歡迎使用ASP.NETMVC!";
returnView();
}
publicActionResultAbout()
{
returnView();
}
//上傳頁面的視圖
publicActionResultUpload()
{
returnView();
}
//上傳文件的控制項name是file1,也就是<inputtype="file"name="file1"/>
//上傳到Upload文件夾(與Controllers文件同級)
[HttpPost]
publicActionResultUploadFile()
{
HttpFileCollectionBasefiles=Request.Files;
HttpPostedFileBasefile=files["file1"];
if(file!=null&&file.ContentLength>0)
{
stringfileName=file.FileName;
//判斷文件名字是否包含路徑名,如果有則提取文件名
if(fileName.LastIndexOf("\")>-1)
{
fileName=fileName.Substring(fileName.LastIndexOf("\")+1);
}
//判斷文件格式,這里要求是JPG格式
if((fileName.LastIndexOf('.')>-1&&fileName.Substring(fileName.LastIndexOf('.')).ToUpper()==".JPG"))
{
stringpath=Server.MapPath("~/Upload/");
try
{
file.SaveAs(path+fileName);
ViewBag.message="上傳成功!";
}
catch(Exceptione)
{
throwe;
}
}
else
{
ViewBag.message="上傳的文件格式不符合要求!";
}
}
else
{
ViewBag.message="上傳的文件是空文件!";
}
returnView("Upload");
}
}
}
視圖文件是Upload.cshtml,這里是視圖代碼:
@{
ViewBag.Title="Upload";
}
<h2>
Upload</h2>
@using(Html.BeginForm("UploadFile","Home",FormMethod.Post,new{enctype="multipart/form-data"}))
{
<inputtype="file"name="file1"/>
<inputtype="submit"value="上傳"/>
}
<div>
@ViewBag.message
</div>

⑧ mvc FilePathResult如何傳遞文件參數
FilePathResult的構造為:
publicFilePathResult(
stringfileName,
stringcontentType
)
第二個參數是content type,就是文件的類型,不同文件類型瀏覽器打開方式不一樣
具體的可以參考:
http://webdesign.about.com/od/multimedia/a/mime-types-by-content-type.htm
http://www.cnblogs.com/chenghm2003/archive/2008/10/19/1314703.html
比如jpg圖片就是"image/jpeg",word文檔就是"application/msword"
⑨ asp.net mvc中如何讀取上傳的doc文件中的數據(含有中文字元)
using Aspose.Words;要引用這個dll
 #region 獲取正文內容
            Byte[] wordbytes = GetReadWord();//獲取文件二進制
            var strFileName = Server.MapPath("~/temp/a.doc");
            var strhtmlFileName = Server.MapPath("~/temp/b.htm");
            var file = File.OpenWrite(strFileName);
            file.Write(wordbytes, 0, wordbytes.Length);
            file.Close();
            file.Dispose();
            Aspose.Words.Document d = new Aspose.Words.Document(strFileName);
            d.Save(strhtmlFileName, SaveFormat.Html);
            var htmlCode = File.ReadAllText(strhtmlFileName, Encoding.GetEncoding("GB2312"));
            File.Delete(strFileName);
            File.Delete(strhtmlFileName);
 #endregion
htmlCode 欄位就是獲取的內容字元串
⑩ jsp在mvc模式下文件上傳
文件的上傳,一般是通過組件來完成的,也沒有什麼mvc模式不模式之分,你可以查下file-upload,或smartupload的使用方法,這兩個組件都能實現上傳操作,試試吧。
