上傳的文件顯示在jsp
① 怎樣將上傳的文件名稱顯示jsp頁面上
... 重命名卜知道``
你上傳文件的時候一般是把路徑存到資料庫嘛``而且那個相對路徑是固定的
那你把路徑存到資料庫之前把把那路徑截取下來 只把文件名存到資料庫嘛``
去取文件名的時候再把相對路徑加上去阿``
這樣的話你資料庫就只存了文件名
這樣你直接把資料庫的文件名顯示到JSP頁面卜就可以了``
② 1、struts2 如何上傳文件並顯示在jsp頁面上,提供下載連接 2、struts2 如何下載顯示在jsp頁面上的文件
http://hi..com/kawnj19890209/blog/item/8c64d78e139c88f4f11f36fa.html可以看看這兒
③ java中如何將文件的內容在顯示在jsp上,也就是在頁面上顯示!謝啦!
首先先把文件的內容讀出來,然後封裝成一個對象或是直接用字元傳送到頁面上,之後就可以在頁面上顯示了。其實主要還是怎麼從文件中讀出內容,怎麼傳遞到頁面上,希望你自己考慮下,然後就成了。
④ jsp文上傳如何實現將上傳的多個文件都同時顯示出來
需要寫一個servlet來處理上傳的文件,你可以修改保存路徑或選擇將圖片保存在資料庫中,只需要做簡單的修改就行了,servlet代碼如下:
package com.ek.servlet;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.ek.image.ImageUtil;
publicclass FileUploadServlet extends HttpServlet {
/**
*
*/
privatestaticfinallong serialVersionUID = 1L;
privatestatic String filePath = "";
/**
* Destruction of the servlet.
*/
publicvoid destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doPost method of the servlet.
*
* 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
*/
publicvoid doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html; charset=UTF-8");
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(4096);
// the location for saving data that is larger than getSizeThreshold()
factory.setRepository(new File(filePath));
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum size before a FileUploadException will be thrown
upload.setSizeMax(1000000);
try {
List fileItems = upload.parseRequest(req);
Iterator iter = fileItems.iterator();
// Get the file name
String regExp = ".+\\\\(.+\\.?())$";
Pattern fileNamePattern = Pattern.compile(regExp);
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
String name = item.getName();
long size = item.getSize();
if ((name == null || name.equals("")) && size == 0)
continue;
Matcher m = fileNamePattern.matcher(name);
boolean result = m.find();
if (result) {
try {
// String type =
// m.group(1).substring(m.group(1).lastIndexOf('.')+1);
InputStream stream = item.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] b = newbyte[1000];
while (stream.read(b) > 0) {
baos.write(b);
}
byte[] imageByte = baos.toByteArray();
String type = ImageUtil.getImageType(imageByte);
if (type.equals(ImageUtil.TYPE_NOT_AVAILABLE))
thrownew Exception("file is not a image");
BufferedImage myImage = ImageUtil
.readImage(imageByte);
// display the image
ImageUtil.printImage(myImage, type, res
.getOutputStream());
// save the image
// if you want to save the file into database, do it here
// when you want to display the image, use the method printImage in ImageUtil
item.write(new File(filePath + "\\" + m.group(1)));
stream.close();
baos.close();
} catch (Exception e) {
e.printStackTrace();
}
} else {
throw new IOException("fail to upload");
}
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (FileUploadException e) {
e.printStackTrace();
}
}
/**
* Initialization of the servlet.
*
* @throws ServletException
* if an error occure
*/
public void init() throws ServletException {
// Change the file path here
filePath = getServletContext().getRealPath("/");
}
}
servlet中使用到一個ImageUtil類,其中封裝了圖片處理的實用方法,用於讀寫圖片,代碼如下:
package com.ek.image;
import java.awt.Component;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.PixelGrabber;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.MemoryCacheImageInputStream;
import net.jmge.gif.Gif89Encoder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.sun.imageio.plugins.bmp.BMPImageReader;
import com.sun.imageio.plugins.gif.GIFImageReader;
import com.sun.imageio.plugins.jpeg.JPEGImageReader;
import com.sun.imageio.plugins.png.PNGImageReader;
/**
* @author Erick Kong
* @see ImageUtil.java
* @createDate: 2007-6-22
* @version 1.0
*/
publicclass ImageUtil {
publicstaticfinal String TYPE_GIF = "gif";
publicstaticfinal String TYPE_JPEG = "jpeg";
publicstaticfinal String TYPE_PNG = "png";
publicstaticfinal String TYPE_BMP = "bmp";
publicstaticfinal String TYPE_NOT_AVAILABLE = "na";
privatestatic ColorModel getColorModel(Image image)
throws InterruptedException, IllegalArgumentException {
PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
if (!pg.grabPixels())
thrownew IllegalArgumentException();
return pg.getColorModel();
}
privatestaticvoid loadImage(Image image) throws InterruptedException,
IllegalArgumentException {
Component mmy = new Component() {
privatestaticfinallong serialVersionUID = 1L;
};
MediaTracker tracker = new MediaTracker(mmy);
tracker.addImage(image, 0);
tracker.waitForID(0);
if (tracker.isErrorID(0))
thrownew IllegalArgumentException();
}
publicstatic BufferedImage createBufferedImage(Image image)
throws InterruptedException, IllegalArgumentException {
loadImage(image);
int w = image.getWidth(null);
int h = image.getHeight(null);
ColorModel cm = getColorModel(image);
GraphicsEnvironment ge = GraphicsEnvironment
.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gd.getDefaultConfiguration();
BufferedImage bi = gc.createCompatibleImage(w, h, cm.getTransparency());
Graphics2D g = bi.createGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
return bi;
}
publicstatic BufferedImage readImage(InputStream is) {
BufferedImage image = null;
try {
image = ImageIO.read(is);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return image;
}
publicstatic BufferedImage readImage(byte[] imageByte) {
ByteArrayInputStream s = new ByteArrayInputStream(imageByte);
BufferedImage image = readImage(s);
return image;
}
publicstaticvoid encodeGIF(BufferedImage image, OutputStream out)
throws IOException {
Gif89Encoder encoder = new Gif89Encoder(image);
encoder.encode(out);
}
/**
*
* @param bi
* @param type
* @param out
*/
publicstaticvoid printImage(BufferedImage bi, String type,
OutputStream out) {
try {
if (type.equals(TYPE_GIF))
encodeGIF(bi, out);
else
ImageIO.write(bi, type, out);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Get image type from byte[]
*
* @param textObj
* image byte[]
* @return String image type
*/
publicstatic String getImageType(byte[] textObj) {
String type = TYPE_NOT_AVAILABLE;
ByteArrayInputStream s = null;
MemoryCacheImageInputStream mcis = null;
try {
s = new ByteArrayInputStream(textObj);
mcis = new MemoryCacheImageInputStream(s);
Iterator itr = ImageIO.getImageReaders(mcis);
while (itr.hasNext()) {
ImageReader reader = (ImageReader) itr.next();
if (reader instanceof GIFImageReader) {
type = TYPE_GIF;
} elseif (reader instanceof JPEGImageReader) {
type = TYPE_JPEG;
} elseif (reader instanceof PNGImageReader) {
type = TYPE_PNG;
} elseif (reader instanceof BMPImageReader) {
type = TYPE_BMP;
}
reader.dispose();
}
} finally {
if (s != null) {
try {
s.close();
} catch (IOException ioe) {
if (_log.isWarnEnabled()) {
_log.warn(ioe);
}
}
}
if (mcis != null) {
try {
mcis.close();
} catch (IOException ioe) {
if (_log.isWarnEnabled()) {
_log.warn(ioe);
}
}
}
}
if (_log.isDebugEnabled()) {
_log.debug("Detected type " + type);
}
return type;
}
privatestatic Log _log = LogFactory.getLog(ImageUtil.class);
}
注意:對gif格式的圖片進行處理的時候,需要另外一下jar包:gif89.jar,因為gif格式的圖片不能使用ImageIO進行輸出。
如需將圖片存放到資料庫中,只需要修改紅色部分,將圖片以blob格式保存到資料庫中,顯示時以byte[]格式讀出,使用ImageUtil.printImage()進行輸出。
⑤ jsp上傳的文件怎樣在網頁中顯示 或者下載
itjob為你解答:如果你上傳在項目的目錄中,可以提供相對路徑顯示,如果是上傳在別的文件夾。就需要顯示相對路徑對應servlet。
⑥ JSP上傳文本文件,並在頁面顯示其內容
jsp上傳文本並顯示內容:
<input type="file" onchange="onFileSelected(event)">
<textarea id="result"></textarea>
function onFileSelected(event) {
var selectedFile = event.target.files[0];
var reader = new FileReader();
var result = document.getElementById("result");
reader.onload = function(event) {
result.innerHTML = event.target.result;
};
reader.readAsText(selectedFile);
}
顯示:
<c:import var="data"
url="http://www.example.com/file.txt"
scope="session"/>
<c:out value="${data}"/>
⑦ 用JSP顯示上傳後的文件列表並下載代碼 大神幫幫忙啊
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<%@page import="com.oreilly.servlet.MultipartRequest"%>
<%@page import="java.io.IOException"%>
<%@page import="java.io.File"%>
<%
request.setCharacterEncoding("UTF-8");
//-----------------------------------------------------------
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
String real=application.getRealPath("/");
String saveDir = application.getRealPath("")+"/Files/";
int maxPostSize = 2000*1024*1024;//
String encoding = "UTF-8";
String fileName = null;
String fileName2 = null;
MultipartRequest multi = null;
MultipartRequest multi2 = null;
try{
multi = new MultipartRequest(request,saveDir,maxPostSize,encoding);
}catch(IOException e){
return;
}
String ContentType="";
Enumeration filesname = multi.getFileNames();
String descs=multi.getParameter("descs");
String staffid=multi.getParameter("staffid");
String yuanName="";//文件原名稱
double size=0.0d;//文件大小,以kb為單位
String error="";
while(filesname.hasMoreElements()){
try{
String name = (String)filesname.nextElement();
fileName = multi.getFilesystemName(name);
out.print("<br/>---"+fileName+"--<br/>");
yuanName=fileName.toString();
File f = multi.getFile(name);
size=f.length();
out.print("<br/>文件大小---"+size+"B--<br/>");
ContentType = fileName.substring(fileName.lastIndexOf(".")+1);
File file=new File(saveDir+fileName);
String newFileName="";
newFileName=String.valueOf(new java.util.Date().getTime())+"."+ContentType;
int fileid=0;
if(file.exists()){
file.renameTo(new File(saveDir+newFileName));
%>
<a href="<%=basePath %>Files/<%=newFileName%>">下載</a>
<%
}
else{
error="請選擇要上傳的文件";
}
}catch(Exception e){ //跳回去
error="請選擇要上傳的文件22";
}
}
%>
</body>
</html>
⑧ j2ee項目web開發用戶上傳頭像jsp頁面顯示問題
1、亂碼把<%@page中的charset=UTF-8
2、文件上傳最簡單的方式:頁面用<file>標簽選擇文件,from提交方式method=multipart/from-data這樣servlet可以直接獲取到頁面的文件輸入輸出流,這樣你可以保存到伺服器,D盤啊隨意什麼位置!
3、servlet想頁面輸出文件,可以獲取jsp的out對象,直接輸出頁面例如:out.write("img<src='路徑'>");即可
⑨ 如何向伺服器上傳一個PPT文件,再將其在jsp中顯示出來,我知道顯示是用iframe標簽
我建議你用iSpring軟體把PPT轉成交互效果相同的Flash然後放在頁面上顯示,不然你自己寫代碼解析PPT,然後自己寫組件顯示效果,太麻煩了。
⑩ 圖片上傳後可以在頁面上顯示出來,那上傳的word文檔如何在JSP頁面上顯示出來呢~~~
一般一個Word或Excel文檔應該先編輯成html頁面再在網站裡面使用吧,你直接使用word,用戶只能下載後才能看到內容,不能在線瀏覽呢。