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

mvc图片上传

发布时间: 2022-02-05 02:24:59

A. 如何在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:纯手打,望采纳)

B. 在MVC中,要实现图片上传并压缩的功能,cshtml,Controller,Model层和Dal层,该如何去写求指点,急用

给你一个上传的插件,这个插件可以做到,先压缩一下在上传

http://fex..com/webuploader/getting-started.html

不过,你觉得不行的话,只能做到上传之后在进行压缩,不管是mvc 还 webform ,都一样,没有任何区别

C. 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>

由于回答超过最大限制,///生成缩略图的代码请向我索取

D. c#MVC 图片上传

请参考http://note.you.com/share/?id=&type=note

E. 在mvc中怎么一次性上传多张图片

http://www.cnblogs.com/chillsrc/archive/2013/01/30/2883648.html
使用pluload 插件
后台
public void UploadFile(HttpContext context)
{
context.Response.CacheControl = "no-cache";
string s_rpath = FileHelper.GetUploadPath();//@"E:\My Documents\Visual Studio 2008\WebSites\SWFUpload\demos\applicationdemo.net";

string Datedir = DateTime.Now.ToString("yy-MM-dd");
string updir = s_rpath + "\\" + Datedir;
string extname = string.Empty;
string fullname = string.Empty;
string filename = string.Empty;
if (context.Request.Files.Count > 0)
{
for (int j = 0; j < context.Request.Files.Count; j++)
{ }

}

F. 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>


G. 求助啊!.net mvc如何实现多张图片的上传

不可以,如果要上传多张,就得多个<input type="file"> ,并且要用name才能获取到。

H. ASP.NET MVC怎么上传图片

/// <summary>
/// 上传图片处理
/// </summary>
/// <param name="ImgType"></param>
/// <returns></returns>
public string CheckImg(HttpPostedFileBase Files,string NameStr)
{
if (Files == null) return "";

string FileType = Files.FileName.Substring(Files.FileName.LastIndexOf(".") + 1);

if (FileType == "gif" || FileType == "GIF" || FileType == "jpg" || FileType == "JPG" || FileType == "png" || FileType == "PNG")
{
//新的文件名
string ImgName = NameStr + DateTime.Now.ToString("yyyyMMddHHmmssfff")+"."+FileType;
Files.SaveAs(Server.MapPath("/schoolUp/"+ImgName));
return ImgName;
}
else
{
return "";
}
}

I. MVC上传图片并显示怎么做呢,最好有demo ,我已经写出一部分但是后台不太会

上传图片前台直接可以用<input type="file">标签来实现,后台接收到文件并保存下来,想要如何处理都可以。

public String SaveFile(MultipartFile imgFile, HttpServletRequest req){
if(!imgFile.isEmpty()) {
try {

//获得后台的真实路径
String realpath=req.getSession().getServletContext().getRealPath("/resource/images");
String pathString=realpath+"/"+imgFile.getOriginalFilename();
System.out.println(pathString);
//在后台保存图片
imgFile.transferTo(new File(pathString));

return pathString;//返回图片存储路径

} catch (IllegalStateException e) {

e.printStackTrace();

}
return null;
}

J. ASP.NET MVC4怎么实现图片上传和预览

之前专门写了个上传插件,希望能帮到你
http://blog.csdn.net/sq111433/article/details/16872403

热点内容
用自己电脑当服务器做网站 发布:2024-10-22 19:46:47 浏览:726
安卓抖音浏览记录在哪里看 发布:2024-10-22 19:29:33 浏览:388
python调用静态方法调用 发布:2024-10-22 19:23:51 浏览:50
php添加文本框 发布:2024-10-22 19:08:08 浏览:484
oracle存储过程定时执行 发布:2024-10-22 19:08:07 浏览:555
vbnet读取数据库数据 发布:2024-10-22 19:06:23 浏览:183
2012文件服务器搭建 发布:2024-10-22 19:04:18 浏览:970
悦动悦目有哪些配置 发布:2024-10-22 18:54:53 浏览:661
BGL编译器手册 发布:2024-10-22 18:54:51 浏览:378
linux使用命令 发布:2024-10-22 18:45:43 浏览:254