当前位置:首页 » 文件管理 » mvc上传文件

mvc上传文件

发布时间: 2022-01-23 23:13:44

① 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的使用方法,这两个组件都能实现上传操作,试试吧。

热点内容
安卓拍光遇视频如何高清 发布:2024-05-05 15:23:20 浏览:932
linuxo文件 发布:2024-05-05 15:19:12 浏览:943
手机服务器地址或者域名 发布:2024-05-05 15:19:09 浏览:372
我的世界服务器版如何登录 发布:2024-05-05 15:17:28 浏览:794
綦江dns服务器地址 发布:2024-05-05 15:04:11 浏览:556
山东省日照市监控服务器地址 发布:2024-05-05 15:03:59 浏览:342
java提升教程 发布:2024-05-05 15:00:51 浏览:144
驱动编译龙芯 发布:2024-05-05 14:41:31 浏览:957
起什么密码 发布:2024-05-05 14:29:48 浏览:562
安卓怎么设置锁屏时不显示微信通话 发布:2024-05-05 14:21:59 浏览:223