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

mvc上传图片

发布时间: 2022-01-11 09:51:20

⑴ 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中,要实现图片上传并压缩的功能,cshtml,Controller,Model层和Dal层,该如何去写求指点,急用

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

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

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

⑶ c#MVC 图片上传

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

⑷ 如何在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 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可以剪切以上的一部分.请自行调整.

⑹ 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;
}

⑺ 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 "";
}
}

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

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

⑼ 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>

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

⑽ java mvc 模式实现图片上传,不需要框架,也不用存入数据库中,

用输入流的方式读入文件

热点内容
安卓美团账号怎么退出 发布:2024-09-28 20:04:52 浏览:851
崩坏三什么服务器可以用邮箱登录 发布:2024-09-28 19:53:50 浏览:202
proxool数据库连接池 发布:2024-09-28 19:41:35 浏览:294
建立企业数据库 发布:2024-09-28 19:31:21 浏览:545
androidapp插件 发布:2024-09-28 19:30:36 浏览:920
linux退出用户 发布:2024-09-28 19:30:25 浏览:926
java查 发布:2024-09-28 19:21:51 浏览:625
pythontimestr 发布:2024-09-28 19:07:30 浏览:866
山村咏怀的算法 发布:2024-09-28 18:37:54 浏览:597
网上存储空间哪家好 发布:2024-09-28 18:07:19 浏览:643