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

java协作开发实现图片上传

发布时间: 2022-10-04 07:15:27

① java实现图片上传至服务器并显示,如何做希望要具体的代码实现

很简单。
可以手写IO读写(有点麻烦)。
怕麻烦的话使用FileUpload组件 在servlet里doPost嵌入一下代码
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
response.setContentType("text/html;charset=gb2312");
PrintWriter out=response.getWriter();

//设置保存上传文件的目录
String uploadDir =getServletContext().getRealPath("/up");
System.out.println(uploadDir);
if (uploadDir == null)
{
out.println("无法访问存储目录!");
return;
}
//根据路径创建一个文件
File fUploadDir = new File(uploadDir);
if(!fUploadDir.exists()){
if(!fUploadDir.mkdir())//如果UP目录不存在 创建一个 不能创建输出...
{
out.println("无法创建存储目录!");
return;
}
}

if (!DiskFileUpload.isMultipartContent(request))
{
out.println("只能处理multipart/form-data类型的数据!");
return ;
}

DiskFileUpload fu = new DiskFileUpload();
//最多上传200M数据
fu.setSizeMax(1024 * 1024 * 200);
//超过1M的字段数据采用临时文件缓存
fu.setSizeThreshold(1024 * 1024);
//采用默认的临时文件存储位置
//fu.setRepositoryPath(...);
//设置上传的普通字段的名称和文件字段的文件名所采用的字符集编码
fu.setHeaderEncoding("gb2312");

//得到所有表单字段对象的集合
List fileItems = null;
try
{
fileItems = fu.parseRequest(request);//解析request对象中上传的文件

}
catch (FileUploadException e)
{
out.println("解析数据时出现如下问题:");
e.printStackTrace(out);
return;
}

//处理每个表单字段
Iterator i = fileItems.iterator();
while (i.hasNext())
{
FileItem fi = (FileItem) i.next();
if (fi.isFormField()){
String content = fi.getString("GB2312");
String fieldName = fi.getFieldName();
request.setAttribute(fieldName,content);
}else{
try
{
String pathSrc = fi.getName();
if(pathSrc.trim().equals("")){
continue;
}
int start = pathSrc.lastIndexOf('\\');
String fileName = pathSrc.substring(start + 1);
File pathDest = new File(uploadDir, fileName);

fi.write(pathDest);
String fieldName = fi.getFieldName();
request.setAttribute(fieldName, fileName);
}catch (Exception e){
out.println("存储文件时出现如下问题:");
e.printStackTrace(out);
return;
}
finally //总是立即删除保存表单字段内容的临时文件
{
fi.delete();
}

}
}
注意 JSP页面的form要加enctype="multipart/form-data" 属性, 提交的时候要向服务器说明一下 此页面包含文件。

如果 还是麻烦,干脆使用Struts 的上传组件 他对FileUpload又做了封装,使用起来更傻瓜化,很容易掌握。

-----------------------------
以上回答,如有不明白可以联系我。

② java 中如何向服务器上传图片

我们使用一些已有的组件帮助我们实现这种上传功能。
常用的上传组件:
Apache 的 Commons FileUpload
JavaZoom的UploadBean
jspSmartUpload
以下,以FileUpload为例讲解
1、在jsp端
<form id="form1" name="form1" method="post" action="servlet/fileServlet" enctype="multipart/form-data">
要注意enctype="multipart/form-data"
然后只需要放置一个file控件,并执行submit操作即可
<input name="file" type="file" size="20" >
<input type="submit" name="submit" value="提交" >
2、web端
核心代码如下:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if (item.isFormField()) {
System.out.println("表单参数名:" + item.getFieldName() + ",表单参数值:" + item.getString("UTF-8"));
} else {
if (item.getName() != null && !item.getName().equals("")) {
System.out.println("上传文件的大小:" + item.getSize());
System.out.println("上传文件的类型:" + item.getContentType());
System.out.println("上传文件的名称:" + item.getName());
File tempFile = new File(item.getName());
File file = new File(sc.getRealPath("/") + savePath, tempFile.getName());
item.write(file);
request.setAttribute("upload.message", "上传文件成功!");
}else{
request.setAttribute("upload.message", "没有选择上传文件!");
}
}
}
}catch(FileUploadException e){
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("upload.message", "上传文件失败!");
}
request.getRequestDispatcher("/uploadResult.jsp").forward(request, response);
}

③ 怎么用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怎样实现图片上传功能

图片不会那么的保存到数据库中。
而是把图片放到文件系统,或者你指定的一个位置。
然后再数据库中存放的为图片的路径

⑤ java实现上传图片功能

首先需要先要在数据库中建立一个数据表格一遍存储和查询,在数据表格中的项中添加数据区和存储路径。数据区用来存储图片,在存储时需要用到转换功能,让图片转换成数据流字符然后才能导入数据库进行存储,并且在输入同时在同一语句中添加存储路径。
希望以上思路能让你有点启发

⑥ java怎样编写发送图片的程序

首先,我们创建一个新的web工程,在工程的WebRoot目录下新建一个upload文件夹,这样当我们将该工程部署到服务器上时,服务器便也生成个upload文件夹,用来存放上传的资源。

然后,在WebRoot目录下新建一个jsp文件,主要实现的作用就是选择上传的文件,提交至servlet来进行处理

详细代码如下:一个form将文件信息通过post方式传送到指定的servlet

<%@pagelanguage="java"import="java.util.*"pageEncoding="utf-8"%>
<%
Stringpath=request.getContextPath();
StringbasePath=
request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%>
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN"><html><head>
<base<%=basePath%>">
<title>MyJSP'upload.jsp'startingpage</title><metahttp-equiv="pragma"content="no-cache">
<metahttp-equiv="cache-control"content="no-cache"><metahttp-equiv="expires"content="0">
<metahttp-equiv="keywords"content="keyword1,keyword2,keyword3"><metahttp-equiv="description"content="Thisismypage"><!--
<linkrel="stylesheet"type="text/css">-->
</head>
<body>
<formaction="/upload/UpLoad"method="post"enctype="multipart/form-data">
请选择上传的图片或文件:<inputtype="file"name="fileName"/><inputtype="submit"value="上传"/>
</form>
</body>
</html>

可以看到,我们将数据提交到工程下的upload/UpLoad。 之后,我们就来编写这个servlet——UpLoad.java

packageload;importjava.io.File;
importjava.io.IOException;importjava.io.PrintWriter;importjava.util.List;
importjavax.servlet.ServletContext;importjavax.servlet.ServletException;importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importmons.fileupload.FileItem;
importmons.fileupload.FileUploadException;importmons.fileupload.disk.DiskFileItemFactory;importmons.fileupload.servlet.ServletFileUpload;{@SuppressWarnings("unchecked")@Override
protectedvoidservice(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,IOException{req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
//为解析类提供配置信息
DiskFileItemFactoryfactory=newDiskFileItemFactory();
//创建解析类的实例
ServletFileUploadsfu=newServletFileUpload(factory);
//开始解析
sfu.setFileSizeMax(1024*400);
//每个表单域中数据会封装到一个对应的FileItem对象上try{
List<FileItem>items=sfu.parseRequest(req);
//区分表单域
for(inti=0;i<items.size();i++){FileItemitem=items.get(i);
varcpro_psid="u2572954";varcpro_pswidth=966;varcpro_psheight=120;
//isFormField为true,表示这不是文件上传表单域if(!item.isFormField()){
ServletContextsctx=getServletContext();
//获得存放文件的物理路径
//upload下的某个文件夹得到当前在线的用户找到对应的文件夹
Stringpath=sctx.getRealPath("/upload");System.out.println(path);
//获得文件名
StringfileName=item.getName();System.out.println(fileName);
//该方法在某些平台(操作系统),会返回路径+文件名
fileName=fileName.substring(fileName.lastIndexOf("/")+1);Filefile=newFile(path+"\"+fileName);if(!file.exists()){item.write(file);
//将上传图片的名字记录到数据库中
resp.sendRedirect("/upload/l");}}}
}catch(Exceptione){e.printStackTrace();}
}
}

因为已对 代码做了详细的注释,所以相信大家也能基本上传的这个过程。要注意的一点是解析实例空间大小的设置。我们希望上传的文件不会是无限大,因此,设置

.setFileSizeMax(1024*400);

⑦ 请问用Java 如何实现图片上传功能

自己写程序来上传字节流文件很难的,用SmartUpload.jar包吧,专门用于JSP上传下载的,唯一缺点就是中文支持不太好,不过你可以改一下原程序的字符集就行了。上网搜,没有找我!我给你发

⑧ 在一个java项目中,怎样实现上传图片的功能

可以使用Apache的common-fileupload组件进行上传。
当然也可以使用其他方式,如ftp上传等,可以用Apache下的common-net工具包。
剩下的就是在servlet、spring等框架中如何使用这些上传工具包。这些框架都有接口实现在那里。调用就可以。

⑨ java实现图片上传至服务器并显示,如何做

给你段代码,是用来在ie上显示图片的(servlet):

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String id = request.getParameter("id");
File file = new File(getServletContext().getRealPath("/")+"out"+"/"+id+".gif");
response.setCharacterEncoding("gb2312");
response.setContentType("doc");
response.setHeader("Content-Disposition", "attachment; filename=" + new String(file.getName().getBytes("gb2312"),"iso8859-1"));

System.out.println(new String(file.getName().getBytes("gb2312"),"gb2312"));

OutputStream output = null;
FileInputStream fis = null;
try
{
output = response.getOutputStream();
fis = new FileInputStream(file);

byte[] b = new byte[1024];
int i = 0;

while((i = fis.read(b))!=-1)
{

output.write(b, 0, i);
}
output.write(b, 0, b.length);

output.flush();
response.flushBuffer();
}
catch(Exception e)
{
System.out.println("Error!");
e.printStackTrace();
}
finally
{
if(fis != null)
{
fis.close();
fis = null;
}
if(output != null)
{
output.close();
output = null;
}
}

}

这个程序的功能是根据传入的文件名(id),来为浏览器返回图片流,显示在<img>标签里
标签的格式写成如下:
<img src="http://localhost:8080/app/preview?id=111 "/><br/>
显示的是111.gif这个图片

你上面的问题:
1.我觉得你的第二个办法是对的,我们也是这样做的,需要的是把数据库的记录id号传进servlet,然后读取这条记录中的路径信息,生成流以后返回就是了

关于上传文件的问题,我记得java中应该专门有个负责文件上传的类,你调用就行了,上传后存储在指定的目录里,以实体文件的形式存放
你可以参考这个:
http://blog.csdn.net/arielxp/archive/2004/09/28/119592.aspx

回复:
1.是的,在response中写入流就行了
2.是发到servlet中的,我们一般都是写成servlet,短小精悍,使用起来方便,struts应该也可以,只是我没有试过,恩,你理解的很对

⑩ 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");
}}