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

圖片上傳java

發布時間: 2022-01-10 12:32:54

『壹』 java怎麼上傳圖片

  1. 使用Commons-FileUpload 上傳文件

  2. Struts 的文件上傳

  3. jspSmartUpload上傳文件

『貳』 java怎樣上傳圖片(寫個例子謝謝);

用struts2框架。。。馬上OK。。。
在響應的ACTION中,只需要定義一個File的變數即可

『叄』 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");
}

}

『肆』 java web開發,上傳圖片並讀取

java web開發中,使用文件操作類來上傳圖片並讀取,如下代碼:

*@desc:圖片處理工具
*@author:bingye
*@createTime:2015-3-17下午04:25:32
*@version:v1.0
*/
publicclassImageUtil{

/**
*將圖片寫到客戶端
*@author:bingye
*@createTime:2015-3-17下午04:36:04
*@history:
*@paramimage
*@paramresponsevoid
*/
publicstaticvoidwriteImage(byte[]image,HttpServletResponseresponse){
if(image==null){
return;
}
byte[]buffer=newbyte[1024];
InputStreamis=null;
OutputStreamos=null;
try{
is=newByteArrayInputStream(image);
os=response.getOutputStream();
while(is.read(buffer)!=-1){
os.write(buffer);
os.flush();
}
}catch(IOExceptione){
e.printStackTrace();
}finally{
try{
if(is!=null){is.close();}
if(os!=null){os.close();}
}catch(IOExceptione){
e.printStackTrace();
}
}
}

/**
*獲取指定路勁圖片
*@author:bingye
*@createTime:2015-3-21上午10:50:44
*@paramfilePath
*@paramresponsevoid
*/
publicstaticvoidwriteImage(StringfilePath,HttpServletResponseresponse){
FileimageFile=newFile(filePath);
if(imageFile!=null&&imageFile.exists()){
byte[]buffer=newbyte[1024];
InputStreamis=null;
OutputStreamos=null;
try{
is=newFileInputStream(imageFile);
os=response.getOutputStream();
while(is.read(buffer)!=-1){
os.write(buffer);
os.flush();
}
}catch(FileNotFoundExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}finally{
try{
if(is!=null){is.close();}
if(os!=null){os.close();}
}catch(IOExceptione){
e.printStackTrace();
}
}
}
}

/**
*圖片上傳到文件夾
*@author:bingye
*@createTime:2015-3-20下午08:07:25
*@paramfile
*@paramsavePath
*@returnboolean
*/
(CommonsMultipartFilefile,StringsavePath){
if(file!=null&&!file.isEmpty()){
//獲取文件名稱
StringfileName=file.getOriginalFilename();
//獲取後綴名
StringsuffixName=fileName.substring(fileName.indexOf(".")+1);
//新名稱
StringnewFileName=System.currentTimeMillis()+"."+suffixName;
//新文件路勁
StringfilePath=savePath+newFileName;
//獲取存儲文件路徑
FilefileDir=newFile(savePath);
if(!fileDir.exists()){
//如果文件夾沒有:新建
fileDir.mkdirs();
}
FileOutputStreamfos=null;
try{
fos=newFileOutputStream(filePath);
fos.write(file.getBytes());
fos.flush();
returnResultUtil.success("UPLOAD_SUCCESS",URLEncoder.encode(newFileName,"utf-8"));
}catch(Exceptione){
e.printStackTrace();
returnResultUtil.fail("UPLOAD_ERROR");
}finally{
try{
if(fos!=null){
fos.close();
}
}catch(IOExceptione){
e.printStackTrace();
returnResultUtil.fail("UPLOAD_ERROR");
}
}
}
returnResultUtil.fail("UPLOAD_ERROR");
}}

『伍』 java實現上傳圖片功能

首先需要先要在資料庫中建立一個數據表格一遍存儲和查詢,在數據表格中的項中添加數據區和存儲路徑。數據區用來存儲圖片,在存儲時需要用到轉換功能,讓圖片轉換成數據流字元然後才能導入資料庫進行存儲,並且在輸入同時在同一語句中添加存儲路徑。
希望以上思路能讓你有點啟發

『陸』 怎麼用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>
這段代碼可以實現普通的文件上傳,有大小限制,上傳普通的圖片肯定沒問題,別的一些小的文件也能傳

『柒』 請問用Java 如何實現圖片上傳功能

自己寫程序來上傳位元組流文件很難的,用SmartUpload.jar包吧,專門用於JSP上傳下載的,唯一缺點就是中文支持不太好,不過你可以改一下原程序的字元集就行了。上網搜,沒有找我!我給你發

熱點內容
長沙java培訓機構哪家好 發布:2024-11-14 12:40:53 瀏覽:228
外存儲器硬碟能存儲的高清電影數 發布:2024-11-14 12:33:23 瀏覽:265
python分號作用 發布:2024-11-14 12:31:50 瀏覽:223
方舟編譯器下載要錢嗎 發布:2024-11-14 12:29:20 瀏覽:62
jspoa源碼 發布:2024-11-14 12:21:31 瀏覽:420
不記得了密碼怎麼辦 發布:2024-11-14 12:18:58 瀏覽:442
python字元串的大小 發布:2024-11-14 12:17:24 瀏覽:222
源碼編輯軟體 發布:2024-11-14 12:15:00 瀏覽:386
java中object 發布:2024-11-14 12:11:48 瀏覽:636
買車時哪些配置需要另外加錢 發布:2024-11-14 12:10:19 瀏覽:534