當前位置:首頁 » 文件傳輸 » 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();