⑴ jsp中怎麼上傳圖片啊
你去網上下載一個smartUpload.jar,然後把這個import到你的處理頁面或者是Servlet中,例如:<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="com.jspsmart.upload.*" %>
<%@page import="s2jsp.bysj.entity.Proct"%>
<%@page import="s2jsp.bysj..ProctDao"%>
<%@page import="s2jsp.bysj..impl.ProctDaoImpl"%><%
SmartUpload su=new SmartUpload();
su.initialize(pageContext);
su.upload();
int count = su.save("/image");
Request req = su.getRequest();
String serialNumber= req.getParameter("serialNumber");
String name=req.getParameter("name");
String brand=req.getParameter("brand");
String model=req.getParameter("model");
String price=req.getParameter("price");
String description=req.getParameter("description");
com.jspsmart.upload.File file = su.getFiles().getFile(0) ;
String picture=file.getFileName();
Proct proct=new Proct();
proct.setSerialNumber(serialNumber);
proct.setName(name);
proct.setBrand(brand);
proct.setModel(model);
proct.setPrice(price);
proct.setPicture(picture);
proct.setDescription(description);
ProctDao =new ProctDaoImpl();
int res=.addProct(proct);
if (res!=1)
{
out.print("<script>alert('添加失敗。');location.href='addProct.html';</script>");
return;
}
out.print("<script>alert('添加成功。');location.href='manageProct.jsp'</script>");
%>
⑵ jsp上傳圖片,最好完整代碼。100分!
upfile.jsp 文件代碼如下:
<form method="post" action="uploadimage.jsp" name="form1" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submIT" name="sub" value="upload">
</form>
<form method="post" action="uploadimage.jsp" name="form1" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" name="sub" value="upload">
</form>
<STRONG><FONT color=#ff0000>uploadimage.jsp</FONT></STRONG>
文件代碼如下:
uploadimage.jsp
文件代碼如下:view plain to clipboardprint?
<PRE class=java name="code"><%@ page language="java" pageEncoding="gb2312"%>
<%@ page import="java.io.*,java.awt.Image,java.awt.image.*,com.sun.image.codec.jpeg.*,java.sql.*,com.jspsmart.upload.*,java.util.*"%>
<%@ page import="mainClass.*" %>
<html>
<head>
<title>My JSP 'uploadimage.jsp' starting page</title>
</head>
<body>
<%
SmartUpload sma=new SmartUpload();
long file_max_size=4000000;
String filename1="",ext="",testvar="";
String url="uploadfiles/";
sma.initialize(pageContext);
try
{
sma.setAllowedFilesList("jpg,gif");
sma.upload();
}catch(Exception e){
%>
<script language="jscript">
alert("只允許上傳jpg,gif圖片")
window.location.href="upfile.jsp"
</script>
<%
}
try{
com.jspsmart.upload.File myf=sma.getFiles().getFile(0);
if(myf.isMissing()){
%>
<script language="jscript">
alert("請選擇要上傳的文件!")
window.location.href="upfile.jsp"
</script>
<%
}else{
ext=myf.getFileExt();
int file_size=myf.getSize();
String saveurl="";
if(file_size < file_max_size){
Calendar cal=Calendar.getInstance();
String filename=String.valueOf(cal.getTimeInMillis());
saveurl=request.getRealPath("/")+url;
saveurl+=filename+"."+ext;
myf.saveAs(saveurl,sma.SAVE_PHYSICAL);
myclass mc=new myclass(request.getRealPath("data/data.mdb"));
mc.executeInsert("insert into [path] values('uploadfiles/"+filename+"."+ext+"')");
out.println("圖片上傳成功!");
response.sendRedirect("showimg.jsp");
}
}
}catch(Exception e){
e.printStackTrace();
}
%>
</body>
</html>
</PRE>
本文來自: IT知道網(http://www.itwis.com) 詳細出處參考:http://www.itwis.com/html/java/jsp/20080916/2409.html
⑶ JSP編寫一個上傳圖片的網頁
如果上傳的話你自己實現,前面的就很簡單了。只要把下面的代碼放在記事本里另存問HTML格式,打開就可以了。
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDHTML4.01Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>upload</title>
<!--metahttp-equiv="Content-Type"content="text/html;charset=iso-885Array-1"-->
<!--metahttp-equiv="Content-Type"content="text/html;charset=gb2312"-->
</head>
<FORMname="form1"METHOD="POST"ACTION="sssupload.jsp"ENCTYPE="multipart/form-data">
<tdclass="bodystyle">file</td>
<tdclass="bodystyle"><inputname="attach"type="FILE"id="attach"size="50"></td>
<inputname="ok"type="submit"value="upload">
</form>
</body>
⑷ JSP如何上傳圖片
jsp使用I/O文件操作類,可以將圖片轉成二進制的形式,然後保存在伺服器中的一個文件夾,示例如下:
<%...@pagecontentType="text/html;charset=gb2312"%>
<%...@pageimport="java.util.*"%>
<%...@pageimport="java.text.*"%>
<%...@pageimport="java.io.*"%>
<%...@pageimport="com.sun.image.codec.jpeg.*"%>
<%...@pageimport="java.awt.image.*"%>
<%...@pageimport="java.awt.*"%>
<%...
Stringname=request.getParameter("name");
name=newString(name.getBytes("ISO-8859-1"));
Stringima=request.getParameter("image");
try{
Stringpath=request.getRealPath("/");
FileOutputStreamot=newFileOutputStream(path+name+".jpg");
//ServletOutputStreamot=response.getOutputStream();//也可以直接輸出顯示
FileInputStreamin=newFileInputStream(ima);
JPEGImageDecoderjpgCodec=JPEGCodec.createJPEGDecoder(in);
BufferedImageimage=jpgCodec.decodeAsBufferedImage();
JPEGImageEncoderencoder=JPEGCodec.createJPEGEncoder(ot);
encoder.encode(image);
in.close();
ot.close();
out.print("JSP上傳圖片成功!<BR>");
//載入上傳成功的圖片
out.print("<IMGwidth=200height=200src='"+name+".jpg'/>");
}
catch(Exceptione)
{
System.out.print(e.toString());
}
%>
⑸ jsp怎麼上傳圖片求代碼!
Apache commons-fileupload是一個很好的文件上傳工具,最近使用commons-fileupload實現了圖片的上傳及顯示,可將圖片保存在指定的文件夾中,也可以將圖片存放在資料庫,並支持四種常用的圖片格式:jpg,png,gif,bmp。
首先,跟上傳一般文件一樣,需要寫一個servlet來處理上傳的文件,你可以修改保存路徑或選擇將圖片保存在資料庫中,只需要做簡單的修改就行了,servlet代碼如下:
FileUploadServlet.java
java 代碼 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; public class FileUploadServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; private static String filePath = ""; /** * Destruction of the servlet.
*/ public void 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 */ public void 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 = new byte[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)) throw new 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("/"); } 請打勾滿意,原創謝謝
⑹ jsp如何上傳圖片到資料庫
jsp上傳圖片到數據,在資料庫中有一種類型就是blob存儲類型,就是用於儲存二進制的。在java.sql裡面的PreparedStatment有個setBlob()方法存入資料庫,還有ResultSet里的getBlob()就是讀取,詳情你可以看JDBC Blob如何使用。
在jsp里上傳圖片很少用上述方式存儲到資料庫中,一般是將圖片上傳到伺服器項目目錄文件夾中,然後資料庫中保存該圖片文件的地址,如/item/upload/images/我上傳的圖片.jpg
⑺ 通過JSP怎樣上傳圖片到伺服器
1.限制文件上傳類型只能是圖片
function checkFileType(name,file){
var extArray = new Array(".doc",".docx");
var allowSubmit = false;
if (!file){
return;
}
while (file.indexOf("\\") != -1){
file = file.slice(file.indexOf("\\") + 1);
}
var ext = file.slice(file.indexOf(".")).toLowerCase();
for (var i = 0; i < extArray.length; i++) {
if (extArray[i] == ext){
allowSubmit = true;
break;
}
}
if(!allowSubmit){
alert("只能上傳以下格式的文件:"+ (extArray.join("")) + "\n請重新選擇再上傳.");
document.getElementById(name).value = "";
}
}
其中:extArray是要求文件類型。可自行定義。
2.引入jQuery外部文件
jquery-2.1.4.min.js
3.編寫js代碼
$(function () {
$('#txtfilePath1').uploadReview({
width: 350,
height: 350,
target: '#uploadReview1_content'
});
});
其中:txtfilePath1是input:file。width,height是預覽圖片的寬度和高度。target是顯示預覽圖片的位置。
4.編寫jsp頁面代碼
<body>
<input type="text" class="yourClassName" name="filePath1" id="filePath1"/>
<input type="file" id="txtfilePath1" name="txtfilePath1" style="display:none;">
<input type="button" onclick="txtfilePath1.click()" id="fileup1" name="fileup1" class="searchThing"value="上傳">
</body>
註: 這個是很久以前在網上看到的,就整理了下來,但是這么久都沒用過,所以也沒調試過,你自己試一試研究研究, 再來網上很多博客里,他們寫的很詳細的,可以去看看