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

jsp图片上传

发布时间: 2022-02-06 00:04:39

⑴ jsp图片上传后图片损坏

导致文件格式错误80%是因为流传输出错 文件输入流一般用的是FileInputStream 或者 inputStream 。把DataInputSteam改成FileInputStream 或者直接用InputStream
试试看

⑵ java上传图片

/**
*
*/
package net.hlj.chOA.action;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.hlj.chOA..DangAnDao;
import net.hlj.chOA..LogDao;
import net.hlj.chOA..ZiYuanDao;
import net.hlj.chOA.model.DangAn;
import net.hlj.chOA.model.User;
import net.hlj.chOA.model.ZiYuan;
import net.hlj.chOA.util.GetId;

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 org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

/**
* @author lcy
*
*/
public class ZiYuanAction extends DispatchAction {

public ActionForward addZiYuan(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
String title = "";
String fileupload="";
SimpleDateFormat fmt = new SimpleDateFormat("yyMMddhhssmmSSS");
Date now = new Date();
String date = fmt.format(now);
String filePath = request.getSession().getServletContext().getRealPath(
"/");
String uploadPath = filePath + "upload\\uploadZiYuan\\";
String tempPath = filePath + "upload\\uploadZiYuan\\" + "uploadTemp";
String suffix = null;
if (!new File(uploadPath).isDirectory()) {
new File(uploadPath).mkdirs();
}
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(4194304);// 设置初始化内存,如果上传的文件超过该大小,将不保存到内存,而且硬盘中(单位:byte)
File fileTemp = new File(tempPath);// 建立临时目录
fileTemp.mkdir();
factory.setRepository(fileTemp);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(4194304);// 设置客户端最大上传,-1为无限大(单位:byte)
try {
List<FileItem> items = upload.parseRequest(request);
Iterator<FileItem> i = items.iterator();
String[] rightType = {".gif", ".jpeg", ".doc", ".xls",
".pdf", ".txt", ".rar" };
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
if (fi.isFormField()) {
try {
if (fi.getFieldName().equals("title")) {
title = fi.getString("UTF-8");
}
} catch (UnsupportedEncodingException e) {
log.error(e.getMessage(), e);
}
} else {
String fileName = fi.getName();
int l = fileName.length();
if (!fileName.equals("")) {
int pos = fileName.lastIndexOf(".");
// suffix = fileName.substring(l - 4, l);
suffix = fileName.substring(pos, l);

boolean result = false;
String ext = fileName.substring(fileName
.lastIndexOf("."));
for (int j = 0; j < rightType.length; j++) {
if (ext.toLowerCase().equals(rightType[j])) {
result = true;
break;
}
}
if (!result) {
request.setAttribute("error", "上传文件类型有误!");
return mapping.findForward("addZiyuan");
}

// if (!suffix.equalsIgnoreCase(".jpg") &&
// !suffix.equalsIgnoreCase(".gif")
// && !suffix.equalsIgnoreCase(".png") &&
// !suffix.equalsIgnoreCase(".bmp")) {
// request.setAttribute("message", "上传文件类型有误!");
// return mapping.findForward("danganList");
// }
if (fileName != null) {
File savedFile = new File(uploadPath, date + suffix);
try {
fi.write(savedFile);
fileupload = "upload/uploadZiYuan/" + date
+ suffix;
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}
}
}
} catch (FileUploadException e) {
log.error(e.getMessage(), e);
}
ZiYuan zy=new ZiYuan();
zy.setTitle(title);
zy.setUpload(fileupload);
ZiYuanDao zyDao=new ZiYuanDao();
try {
zyDao.addZiYuan(zy, this.servlet.getServletContext());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
LogDao lDao=new LogDao();
//删除操做添加日志 isDel 0是增加,1是删除,2是修改,3是审批
User user1 =(User)request.getSession().getAttribute("userBean");
String ip=request.getLocalAddr();
int id=GetId.getId("ziyuan", this.servlet.getServletContext());
try {
lDao.addLogMe("ziyuan", id , ip, user1.getName(), user1.getId(), 0, this.servlet.getServletContext());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mapping.findForward("ziyuanList");
}

public ActionForward deleteZiYuan(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
String[] ids= request.getParameterValues("id");
ZiYuanDao zyDao=new ZiYuanDao();
LogDao lDao=new LogDao();
for(int i=0;i<ids.length;i++){
try {
zyDao.deleteZiYuan(Integer.parseInt(ids[i]), this.servlet.getServletContext());
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
User user =(User)request.getSession().getAttribute("userBean");
String ip=request.getLocalAddr();
try {
lDao.addLogMe("tbl_users",Integer.parseInt(ids[i]), ip, user.getName(), user.getId(), 1, this.servlet.getServletContext());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
return mapping.findForward("ziyuanList");
}

public ActionForward updateZiYuan(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws NumberFormatException, SQLException {
String id="";
String title = "";
String fileupload="";
SimpleDateFormat fmt = new SimpleDateFormat("yyMMddhhssmmSSS");
Date now = new Date();
String date = fmt.format(now);
String filePath = request.getSession().getServletContext().getRealPath(
"/");
String uploadPath = filePath + "upload\\uploadZiYuan\\";
String tempPath = filePath + "upload\\uploadZiYuan\\" + "uploadTemp";
String suffix = null;
if (!new File(uploadPath).isDirectory()) {
new File(uploadPath).mkdirs();
}
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(4194304);// 设置初始化内存,如果上传的文件超过该大小,将不保存到内存,而且硬盘中(单位:byte)
File fileTemp = new File(tempPath);// 建立临时目录
fileTemp.mkdir();
factory.setRepository(fileTemp);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(4194304);// 设置客户端最大上传,-1为无限大(单位:byte)
try {
List<FileItem> items = upload.parseRequest(request);
Iterator<FileItem> i = items.iterator();
String[] rightType = {".gif", ".jpeg", ".doc", ".xls",
".pdf", ".txt", ".rar" };
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
if (fi.isFormField()) {
try {
if (fi.getFieldName().equals("title")) {
title = fi.getString("UTF-8");
}
if (fi.getFieldName().equals("id")) {
id = fi.getString("UTF-8");
}
} catch (UnsupportedEncodingException e) {
log.error(e.getMessage(), e);
}
} else {
String fileName = fi.getName();
int l = fileName.length();
if (!fileName.equals("")) {
int pos = fileName.lastIndexOf(".");
// suffix = fileName.substring(l - 4, l);
suffix = fileName.substring(pos, l);

boolean result = false;
String ext = fileName.substring(fileName
.lastIndexOf("."));
for (int j = 0; j < rightType.length; j++) {
if (ext.toLowerCase().equals(rightType[j])) {
result = true;
break;
}
}
if (!result) {
request.setAttribute("error", "上传文件类型有误!");
request.setAttribute("id", id);
return mapping.findForward("selectZiyuan");
}

// if (!suffix.equalsIgnoreCase(".jpg") &&
// !suffix.equalsIgnoreCase(".gif")
// && !suffix.equalsIgnoreCase(".png") &&
// !suffix.equalsIgnoreCase(".bmp")) {
// request.setAttribute("message", "上传文件类型有误!");
// return mapping.findForward("danganList");
// }
if (fileName != null) {
File savedFile = new File(uploadPath, date + suffix);
try {
fi.write(savedFile);
fileupload = "upload/uploadZiYuan/" + date
+ suffix;
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}else{
//这里写如果用户没有重写添加附件则保持原来的附件
ZiYuanDao zyDao = new ZiYuanDao();
ZiYuan zy=(ZiYuan)zyDao.selectZiYuanById(Integer.parseInt(id), this.servlet.getServletContext()).get(0);
fileupload=zy.getUpload();
}
}
}
} catch (FileUploadException e) {
log.error(e.getMessage(), e);
}
ZiYuan zy=new ZiYuan();
zy.setId(Integer.parseInt(id));
zy.setTitle(title);
zy.setUpload(fileupload);
ZiYuanDao zyDao=new ZiYuanDao();
try {
zyDao.updateZiYuan(zy, this.servlet.getServletContext());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
LogDao lDao=new LogDao();
//删除操做添加日志 isDel 0是增加,1是删除,2是修改,3是审批
User user1 =(User)request.getSession().getAttribute("userBean");
String ip=request.getLocalAddr();
try {
lDao.addLogMe("ziyuan", Integer.parseInt(id) , ip, user1.getName(), user1.getId(), 2, this.servlet.getServletContext());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return mapping.findForward("ziyuanList");
}

}

⑶ 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上传图片,最好完整代码。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中怎么上传图片啊

你去网上下载一个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>");
%>

⑹ Java图片上传处理

upload.jsp
<%@ page contentType="text/html; charset=gb2312" language="java" import="java.util.*,com.jspsmart.upload.*" %>
<html>
<head>
<title>上传文件 </title>

</head>
<body>
<form id="form1" name="msform" method="post" action="do_upload.jsp" enctype="multipart/form-data" onSubmit="return Check_Found(this);" target="iframe1">
<table width="50%" border="1" align="center">
<tr>
<td align="center"><input type="text" name="name" id="text1"></td>
</tr>
<tr>
<td align="center">产品说明:
<input type="file" name="file2" value=""/>
<iframe name="iframe1" style="display:none"> </iframe>
<input type="submit" name="Submit" value="上传图片" />
</td>
</tr>
</table>
</form>
</body>
</html>

do_upload.jsp
<%@ page contentType="text/html; charset=gb2312" language="java" import="java.util.*,com.jspsmart.upload.*" %>
<html>
<head>
<title>文件上传处理页面 </title>

</head>
<body>
<%
SmartUpload su=new SmartUpload();
su.initialize(pageContext);
su.upload();
String name;
int count=su.save("/upload",su.SAVE_VIRTUAL);
out.println(count+"个文件上传成功! <br>");
for(int i=0;i <su.getFiles().getCount();i++)
{
com.jspsmart.upload.File file=su.getFiles().getFile(i);
if(file.isMissing()) continue;
String files=file.getFileName();
out.print("<script>window.parent.document.text1.value='../upload/"+file.getFileName()+"';</script>");
out.print("<script>alert('上传成功!');</script>");
response.setHeader("Refresh","0;URL=addnewproce.jsp");
}
%>
</body>
</html>

还需要组件才行

⑺ java怎么上传图片

  1. 使用Commons-FileUpload 上传文件

  2. Struts 的文件上传

  3. jspSmartUpload上传文件

⑻ 怎么用Java实现图片上传

下面这是servlet的内容:
package demo;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

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.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class DemoServlet extends HttpServlet {

private static final String UPLOAD_DIRECTORY = "upload";
private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB
private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
DiskFileItemFactory factory=new DiskFileItemFactory();
ServletFileUpload sfu=new ServletFileUpload(factory);
sfu.setHeaderEncoding("UTF-8");
sfu.setProgressListener(new ProgressListener() {

public void update(long pBytesRead, long pContentLength, int pItems) {
System.out.println("文件大小为:"+pContentLength+",当前已处理:"+pBytesRead);

}
});
//判断提交上来的数据是否是上传表单的数据
if(!ServletFileUpload.isMultipartContent(request)){
PrintWriter writer= response.getWriter();
writer.println("Error:表单必须包含 enctype=multipart/form-data");
writer.flush();
return;
}
factory.setSizeThreshold(MEMORY_THRESHOLD);
//设置临时储存目录
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
//设置最大文件上传值
sfu.setFileSizeMax(MAX_FILE_SIZE);
//设置最大请求值(包含文件和表单数据)
sfu.setSizeMax(MAX_REQUEST_SIZE);
String uploadpath=getServletContext().getRealPath("./")+ File.separator+UPLOAD_DIRECTORY;
File file=new File(uploadpath);
if(!file.exists()){
file.mkdir();
}

try {
List<FileItem> formItems = sfu.parseRequest(request);
if(formItems!=null&&formItems.size()>0){
for(FileItem item:formItems){
if(!item.isFormField()){
String fileName=new File(item.getName()).getName();
String filePath=uploadpath+File.separator+fileName;
File storeFile=new File(filePath);
System.out.println(filePath);
item.write(storeFile);
request.setAttribute("message", "文件上传成功!");
}
}
}
} catch (Exception e) {
request.setAttribute("message", "错误信息:"+e.getMessage());
}
getServletContext().getRequestDispatcher("/demo.jsp").forward(request, response);
}

}

下面是jsp的内容,jsp放到webapp下,如果想放到WEB-INF下就把servlet里转发的路径改一下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="demo.do" enctype="multipart/form-data" method="post">
<input type="file" name="file1" />
<%
String message = (String) request.getAttribute("message");
%>
<%=message%>
<input type="submit" value="提交"/>
</form>
</body>
</html>
这段代码可以实现普通的文件上传,有大小限制,上传普通的图片肯定没问题,别的一些小的文件也能传

⑼ jsp上传jpg图片问题

在index.jsp页面的form里,指定method属性为post,encType="multipart/form-data"

这是Servlet里的代码:

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
//这里我们需要实现文件上传的效果
SmartUpload su = new SmartUpload();//new出一个对象,即声明对象
//完成smartupload初始化,传入相关的参数
su.initialize(this.getServletConfig(), request, response);
//这步上传文件
try {
//相当于文件读取流
su.upload();

Files files = su.getFiles();
int count = files.getCount();
System.out.println("The count of files is :"+count);
//循环对每个文件进行处理
for(int i=0;i < count;i ++){
File f = files.getFile(i);
//文件不为空的时候上传
if(!f.isMissing()){
f.saveAs("d:\\img\\22.jpg",File.SAVEAS_PHYSICAL);//指定文件保存的路径及文件名
}
}
} catch (SmartUploadException e) {
e.printStackTrace();
}
}

希望对你有所帮助。

⑽ jsp上传图片问题

单纯的写个输入流也可以实现,

FileInputStream str = new FileInputStream("D:/test.jpg"); 之前加上如下创建文件的语句就行

File ff=new File("F:/bbb.jpp");
ff.createNewFile();