当前位置:首页 » 文件管理 » 图片上传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上传下载的,唯一缺点就是中文支持不太好,不过你可以改一下原程序的字符集就行了。上网搜,没有找我!我给你发

热点内容
网易苹果游戏怎么转移到安卓 发布:2024-11-15 00:07:52 浏览:270
win7php环境搭建 发布:2024-11-15 00:06:55 浏览:17
erpjava 发布:2024-11-14 23:52:23 浏览:253
电脑版地平线四怎么连上服务器 发布:2024-11-14 23:46:42 浏览:472
ios怎么变安卓 发布:2024-11-14 23:46:36 浏览:333
win7共享xp打印机拒绝访问 发布:2024-11-14 23:45:29 浏览:750
引起资源配置失效的原因有哪些 发布:2024-11-14 23:35:22 浏览:15
c语言打字 发布:2024-11-14 23:11:06 浏览:893
存储程序和程序控制的原理 发布:2024-11-14 22:53:23 浏览:323
python读取json数据 发布:2024-11-14 22:51:52 浏览:931