当前位置:首页 » 文件传输 » jsp网站上传图片
扩展阅读
webinf下怎么引入js 2023-08-31 21:54:13
堡垒机怎么打开web 2023-08-31 21:54:11

jsp网站上传图片

发布时间: 2022-07-18 20:48:00

⑴ 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>

注: 这个是很久以前在网上看到的,就整理了下来,但是这么久都没用过,所以也没调试过,你自己试一试研究研究, 再来网上很多博客里,他们写的很详细的,可以去看看