當前位置:首頁 » 文件管理 » jsp上傳圖片顯示

jsp上傳圖片顯示

發布時間: 2023-08-14 19:10:39

『壹』 jsp如何上傳照片到mysql,再查詢在jsp中顯示

1 mysql存儲大容量的二進制文件的格式是longblob ,其實除了圖片還可以存別的

CREATE TABLE `abc`.`images` (
`name` varchar(10) NOT NULL,
`chang` int(10) unsigned NOT NULL,
`content` longblob NOT NULL,
PRIMARY KEY (`name`)
)

ENGINE=InnoDB DEFAULT CHARSET=utf8;

2 要向資料庫存儲二進制的文件一定要把要存儲的數據轉換成二進制流
廢話就不多說了,大家看看代碼很容易明白,先來看一個app程序,當然首先您要在資料庫中先建立一個用於保存圖片的表和相應的列,
數據格式為blob
package com.lizhe;
import java.io.*;
import java.sql.*;
public class PutImg {
public void putimg() {
try {
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
String url = "jdbc:mysql://localhost/img?user=root&password=root&useUnicode=true&characterEncoding=gbk";
Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement();
//stmt.execute("insert into imgt (id) values (5)");
stmt.close();
PreparedStatement pstmt = null;
String sql = "";
File file = new File("c:\\blog.jpg");
InputStream photoStream = new FileInputStream(file);
//sql = " UPDATE imgt SET img = ? ";

sql = "INSERT INTO imgtable (img) VALUES (?)";

pstmt = conn.prepareStatement(sql);
pstmt.setBinaryStream(1, photoStream, (int) file.length());
pstmt.executeUpdate();
pstmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]){
PutImg pi=new PutImg();
pi.putimg();
}
}

InputStream photoStream = new FileInputStream(file);
可以很清楚的看到我們首先把一個圖片文件(當然也可以是別的什麼文件)轉換成了一個二進制輸慎和型入流
pstmt.setBinaryStream(1, photoStream, (int) file.length());
這個方法建議大家去查一下API文檔,第一個參數是通配符位置沒的說,第二個參數是流,這和以往的string類型的參數不太一樣,
我剛看到的時候也覺得豁然開朗了,但是到這里還沒完,不同於以往的字元串寬猜參數,這里我們還需要第三個參數來棚祥設置這個流的長度,
這里也就是這個文件的長度,導出資料庫中的sql,一切都清楚了
INSERT INTO `m_diy` VALUES (2,?\0 JFIF\0 \0H\0H\0\0?? Exif\0\0MM\0*\0\0\0 \0 \0 \0\0\0 \0 \0\0 \0 \0\0\0 \0\0\0b
\0 \0\0\0 \0\0\0j (\0 \0\0\0 \0 \0\0 1\0 \0\0\0 \0\0\0r 2\0 \0\0\0 \0\0\0?i\0 \0\0\0 \0\0\0\0\0\0\0\0\0H\0\0\0
\0\0\0H\0\0\0 Adobe Photoshop CS Windows\02007:03:18 23:08:15\0\0\0\0\0 ?\0 \0\0\0 ??\0\0?\0 \0\0\0 \0\0\0? \0
........等等
其實就是將文件先轉換成了二進制的流,然後插入到了sql語言中,向資料庫寫入了很長很長的一段sql語句

然後我們再來寫一個app程序將這個文件讀出來,存儲成一個圖片文件
package com.lizhe;
import java.io.*;
import java.sql.*;
class GetImg {

private static final String URL = "jdbc:mysql://localhost/img?user=root&password=root&useUnicode=true&characterEncoding=gbk";
private Connection conn = null;
private PreparedStatement pstmt = null;
private ResultSet rs = null;
private File file = null;

public void blobRead(String outfile, int picID) throws Exception {
FileOutputStream fos = null;
InputStream is = null;
byte[] Buffer = new byte[4096];
try {
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
conn = DriverManager.getConnection(URL);
pstmt = conn.prepareStatement("select img from imgt where id=?");
pstmt.setInt(1, picID); // 傳入要取的圖片的ID
rs = pstmt.executeQuery();
rs.next();
file = new File(outfile);
if (!file.exists()) {
file.createNewFile(); // 如果文件不存在,則創建
}
fos = new FileOutputStream(file);
is = rs.getBinaryStream("img");
int size = 0;

while ((size = is.read(Buffer)) != -1) {
// System.out.println(size);
fos.write(Buffer, 0, size);
}
} catch (Exception e) {
System.out.println( e.getMessage());
} finally {
// 關閉用到的資源
fos.close();
rs.close();
pstmt.close();
conn.close();
}
}
public static void main(String[] args) {
try {
GetImg gi=new GetImg();
gi.blobRead("c:/getimgs/1.jpg", 5);
} catch (Exception e) {
System.out.println("[Main func error: ]" + e.getMessage());
}
}
}
這里需要注意的是
is = rs.getBinaryStream("img");
img是資料庫中相應的列名,其實和rs.getString()方法差不多,只不過這個方法是讀取二進制流的
最後在帖兩個bs系統上用的文件給大家參考
通過struts的action向資料庫寫入二進制圖片
/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.lizhe.struts.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import com.lizhe.struts.form.UpimgForm;
/**
* MyEclipse Struts
* Creation date: 05-18-2007
*
* XDoclet definition:
* @struts.action path="/upimg" name="upimgForm" input="/userhomepage.jsp"
* @struts.action-forward name="userhome" path="/userhomepage.jsp" redirect="true" contextRelative="true"
*/
public class UpimgAction extends Action {
/*
* Generated Methods
*/
/**
* Method execute
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
* @throws IOException
* @throws FileNotFoundException
*/
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException, IOException {
UpimgForm upimgForm = (UpimgForm) form;// TODO Auto-generated method stub

FormFile file=upimgForm.getFile();
InputStream is=file.getInputStream();

try {
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
String url = "jdbc:mysql://localhost/blog?user=root&password=root&useUnicode=true&characterEncoding=gb2312";
Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement();
//stmt.execute("insert into img (id) values (5)");
stmt.close();
PreparedStatement pstmt = null;
String sql = "";
//File file = new File("c:\\blog.jpg");
//InputStream photoStream = new FileInputStream(file);
//sql = " UPDATE imgt SET img = ? ";

sql = "INSERT INTO img (img) VALUES (?)";

pstmt = conn.prepareStatement(sql);
pstmt.setBinaryStream(1, is, (int) file.getFileSize());
pstmt.executeUpdate();
pstmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}

return mapping.findForward("userhomepage");
}
}
和app的方式幾乎是一樣的
第二個文件是通過jsp將資料庫中的圖片顯示在頁面上
這個有些不同
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.sql.*" %>
<%@ page import="java.util.*"%>
<%@ page import="java.text.*"%>
<%@ page import="java.io.*"%>
<%@ page import="java.awt.*"%>
<html>
<body>
<%
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
String url="jdbc:mysql://localhost/img?user=root&password=root";
Connection con = DriverManager.getConnection(url);
String sql = "select * from imgt where id=5";
Statement stmt = con.createStatement();

ResultSet rs = stmt.executeQuery(sql);
if(rs.next()) {
InputStream in = rs.getBinaryStream("img");
ServletOutputStream op = response.getOutputStream();
int len;
byte[] buf=new byte[1024];
while((len= in.read(buf))!=-1) {
op.write(buf, 0, len);
}
op.close();
in.close();
}

rs.close();
stmt.close();
con.close();
%>
</body>
</html>

『貳』 jsp+servlet 上傳圖片並顯示出來

其實你這個擋也顯示圖片其實很簡單的,
你的需求無非是兩個
1.servlet上傳文件(圖片)
2.點擊 瀏覽 圖標,然後選擇圖片文件,然後就可以在頁面中的某個地方看到圖片

是這兩個需求么?
首先說第二個吧。
你上傳圖片之後,就馬上觸發js函數,內容為
var PicPath = document.getElementById("yourfile").value;
document.getElementById("yourDiv").innerHTML="<IMG src="+PicPath+"/>";
OK了

第一個嘛就無所謂說了,不過我還是貼一個代碼吧,
public void upLoadFile(HttpServletRequest request, HttpServletResponse response) {
PrintWriter out = null;
response.setCharacterEncoding("UTF-8");
//實例化文件工廠
FileItemFactory factory = new DiskFileItemFactory();
//配置上傳組件ServletFileUpload
ServletFileUpload upload = new ServletFileUpload(factory);
try {
out = response.getWriter();
//從request得到所有上傳域的列表
List<FileItem> list = upload.parseRequest(request);

for (FileItem item : list) {
//isFormField判斷一個item類對象封裝的是一個普通的表單欄位還是文件表單欄位。
// 如果item是文件域,則做出如下處理:
if (!item.isFormField()) {

//上傳文件域的Name
String fileName = item.getName();

//截取擴展名
int idx = fileName.lastIndexOf(".");
String extension = fileName.substring(idx);

//獲取文件名
String name = new Date().getTime() + extension;

//得到文件夾的物理路徑
String path = this.getServletContext().getRealPath("\\upload");

//創建一個File
File file = new File(path + "\\" + name);
FileOutputStream o = new FileOutputStream(file);
InputStream in = item.getInputStream();
try {
LoadProcessServlet.process = 0;
LoadProcessServlet.total = 100;
LoadProcessServlet.isEnd = false;
LoadProcessServlet.total = item.getSize();
byte b[] = new byte[1024];
int n;
while ((n = in.read(b)) != -1) {
LoadProcessServlet.process+=n;
o.write(b, 0, n);
System.out.println("實際:"+LoadProcessServlet.process);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
LoadProcessServlet.isEnd = true;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}

}

『叄』 求大神,jsp上上傳圖片,並顯示出來,將其相對路徑記入資料庫


Stringtime=newSimpleDateFormat("yyyyMMddHHmmss")

.format(Calendar.getInstance().getTime());//得到系統時間

//上傳技術

SmartUploap=newSmartUpload();


//進行初始化


up.initialize(this.getServletConfig(),request,response);


//開始上傳


try{

up.upload("utf-8");//設置編碼方式。

intid=Integer.parseInt(up.getRequest().getParameter("id"));//商品編號

SmartFilessf=up.getFiles();//得到上傳的所有圖片

SmartFilefile=sf.getFile(0);//根據索引得到上傳圖片多個圖片可以用循環:

Stringtype=file.getFileExt();//得到圖片後綴名

Stringfolder="tp/";//指定文件夾

Stringpath=folder+time+"."+type;//路徑

System.out.println(path+"路徑");

file.saveAs(request.getRealPath("/")+path);//保存圖片


}catch(Exceptione){

e.printStackTrace();

}

//你搞個郵箱我把SmartUploadjar包發給你吧。 //設置from提交

/*<form action="SellerServet" method="post"

enctype="multipart/form-data">*/ // 加上enctype="multipart/form-data

『肆』 jsp中,我在一個頁面,用jspsmartupload上傳圖片,上傳成功後,跳回來,想顯示此圖,但是顯示不出來。

1.上傳失敗,圖片位元組大小為0KB,需重新上傳覆蓋。
2.源文件的所在的目錄路徑不對。
3.圖片命名的格式不支持:不要用漢字為圖片命名,最好是純英文字母,一般數字也可以。
不知道能幫上不

『伍』 jsp上傳圖片到tomcat伺服器後,怎麼在頁面顯示

你可能把伺服器的相對地址保存到資料庫里去,如在updateimg文件夾下的2012010501.jsp文件
地址就是:/updateimg/2012010501.jsp 前面加上服務的訪問地址

熱點內容
map訪問 發布:2025-02-02 06:09:07 瀏覽:822
android獲取應用版本 發布:2025-02-02 05:54:19 瀏覽:746
pythonif比較 發布:2025-02-02 05:24:03 瀏覽:259
已連接的無線網如何知道密碼 發布:2025-02-02 04:53:51 瀏覽:634
android編程入門經典pdf 發布:2025-02-02 04:46:19 瀏覽:57
安卓什麼軟體測試手機電池 發布:2025-02-02 04:28:52 瀏覽:996
手機上傳快 發布:2025-02-02 04:27:46 瀏覽:308
電腦配置詳解圖解都有哪些 發布:2025-02-02 04:26:27 瀏覽:716
景區應該有什麼配置 發布:2025-02-02 04:09:08 瀏覽:120
c語言與java工作 發布:2025-02-02 03:59:57 瀏覽:283