mvc上傳圖片並顯示
㈠ mvc視圖中怎麼上傳圖片並顯示
直接用 <input type="file"/>
controller 用HttpPostedFile 接受存到固定目錄,然後把文件名和目錄存資料庫,顯示就是讀取資料庫的目錄。
㈡ MVC圖書管理實現上傳圖片功能
展開全部
如果只是上傳的話那太容易了,如果還要顯示那就難了,因為要顯示的話就不能只向伺服器提交一次請求,必須非同步提交。下面的例子是我親自寫的,非同步提交上傳圖片並預覽。全部代碼都在。
首先建一個html文件,復制以下html文本。使用說明:
引用jquery兩個js文件,網上自己搜吧,到處都有。
<script src="jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="jquery.form.js" type="text/javascript"></script>
2.添加兩個文本框,第一個ID必須是「bigImage1」,第二個必須是「smallbigImage1」。
<input type="text" name="url1" id="bigImage1" style="width:150px;" onclick="selectImage(this)" />
<input type="hidden" name="smallUrl1" id="smallbigImage1" value="" />
當點擊第一個文本框時,彈出一個上傳窗口,選擇一張圖片並點「上傳」,上傳成功後可預覽圖片。此過程會在伺服器上把原圖片生成一張縮略圖,並把原圖URL和縮略圖URL一起以JSON格式返回到前台頁面,臨時顯示縮略圖。當點擊「確定」時,它會把兩個URL添加到兩個對應ID的文本框。第二個框是隱藏的,給用戶的感覺就像是只返回一個URL一樣。
㈢ MVC怎麼把圖片顯示出來
src 後面把圖片儲存的全部路徑,/img/r_logo.png 還不全 獲取img 所在的根目錄再把/img/r_logo.png 拼接上
㈣ .net mvc用uploadify 插件上傳圖片上FTP,上傳成功之後怎麼把圖片顯示在前台頁面
你能獲取到圖片對象嗎?
Javascript
文件流. FileReader
======================================================================
///創建一個文件讀取對象
var reader = new
FileReader();
//監聽Onload完成
reader.onload =
function(e){$('#img1').attr('src',e.target.result)}
//
function
(e){$('#img1').attr('src',e.target.result)}
//讀取Url
reader.readAsDataURL(data.files[0])
這樣就可以獲取到bit64格式的url 直接當成Url就行了。
㈤ 如何在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:純手打,望採納)
㈥ asp.net如何實現mvc上傳圖片並顯示進度條呢
那個要做FLASH來實現。asp.net實現不了。
㈦ asp.net mvc3怎麼上傳圖片和顯示圖片
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using PersonalWebSite.UI.Common;
namespace PersonalWebSite.UI
{
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"ArticleClassification", // 導航路由(帶參數)
"article_{classificationId}_{pageCount}_{pageIndex}
㈧ mvc視圖中怎麼上傳圖片並顯示
最簡單的使用input file非同步上傳,或者直接使用 uploadify 非常好的一個上傳插件,非同步,多任務,進度條
㈨ 如何在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可以剪切以上的一部分.請自行調整.
㈩ 如何在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可以剪切以上的一部分.請自行調整.
希望能夠幫助你.