當前位置:首頁 » 文件管理 » 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 模式實現圖片上傳,不需要框架,也不用存入資料庫中,

用輸入流的方式讀入文件

熱點內容
php中替換字元串 發布:2024-09-28 22:01:48 瀏覽:581
sql資料庫的使用 發布:2024-09-28 22:01:41 瀏覽:626
你們的wifi密碼多少 發布:2024-09-28 21:53:07 瀏覽:376
android訪問伺服器 發布:2024-09-28 21:48:46 瀏覽:733
安卓平板如何實現電腦雙擊 發布:2024-09-28 21:27:11 瀏覽:360
德育php 發布:2024-09-28 21:24:36 瀏覽:17
企業密信如何登錄伺服器ld 發布:2024-09-28 21:22:52 瀏覽:463
通過ip不能訪問網站 發布:2024-09-28 21:21:47 瀏覽:523
c語言取整數部分 發布:2024-09-28 21:17:59 瀏覽:66
進來學編程 發布:2024-09-28 21:01:17 瀏覽:966