java做图片上传的代码 javaweb实现图片上传

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://img.readke.com/240909/0205535934-0.jpg"/br/
显示的是111.gif这个图片
你上面的问题:
1.我觉得你的第二个办法是对的,我们也是这样做的,需要的是把数据库的记录id号传进servlet,然后读取这条记录中的路径信息,生成流以后返回就是了
关于上传文件的问题,我记得java中应该专门有个负责文件上传的类,你调用就行了,上传后存储在指定的目录里,以实体文件的形式存放
你可以参考这个:
回复:
1.是的,在response中写入流就行了
2.是发到servlet中的 , 我们一般都是写成servlet,短小精悍 , 使用起来方便,struts应该也可以,只是我没有试过,恩,你理解的很对
求JAVA上传图片代码package com;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import com.jspsmart.upload.*;
public class uploadfiles extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException
{
//使用了一个第三方的组件,存放在web-inf/lib下
response.setContentType("text/html;charset=GB2312");
//由于SmartUpload的初始化方法需要pageContext,所以我们在servlet中得到他
//为了得到pageConext要首先得到JspFactory的实例
//通过JspFactory的实例的getPageContext方法得到pageConext的实例
JspFactory jf = null;
//得到JspFactory的实例
jf=JspFactory.getDefaultFactory();
/*
getPageContext(Servlet servlet,
ServletRequest request,
ServletResponse response,
java.lang.String errorPageURL,
boolean needsSession,
int buffer,
boolean autoflush)
*/
PageContext pageContext=jf.getPageContext(this,request,response,null,true,8192,true);
try
{
//实例化SmartUpload
SmartUpload mySmartUpload=new SmartUpload();
//初始化SmartUpload的实例,需要PageContext的实例
mySmartUpload.initialize(pageContext);
//设定最大上传的字节数,其实可以不进行设定 , 表示上传的文件没有大小限制
//mySmartUpload.setTotalMaxFileSize(10000000);
mySmartUpload.upload();
//下面是单文件上传
//上传的文件以com.jspsmart.upload.File 代表,如果文件名称重复 , 则进行覆盖
com.jspsmart.upload.File file=mySmartUpload.getFiles().getFile(0);
String upLoadFileName=file.getFileName();
//调用com.jspsmart.upload.File实例的saveas的方法保存文件,此时的文件名即是
//保存到服务器上的文件名
file.saveAs("/upload/" upLoadFileName);
Request req =
Text t = .....;
t.setUpload(upLoadFileName);
t.set.....(req);
}
catch(SmartUploadException e)
{
System.out.println(e.getMessage());
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException
{
doGet(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 {
ListFileItem formItems = sfu.parseRequest(request);
if(formItems!=nullformItems.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" ""
html
head
meta http-equiv="Content-Type" content="text/html; charset=UTF-8"
titleInsert 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="/uploads/allimg/240909/0205535934-0.jpg提交"/
/form
/body
/html
这段代码可以实现普通的文件上传,有大小限制,上传普通的图片肯定没问题,别的一些小的文件也能传
解释一下这段JAVA 关于图片上传的代码private File file;
private String fileFileName;
private String picture;
//都有getter 和 setter
InputStream is = new FileInputStream(file);
//引入一个IO流java做图片上传的代码的输入流
String root = ServletActionContext.getRequest()
【java做图片上传的代码 javaweb实现图片上传】.getRealPath("/bookpicture");
//通过REQUEST来得到相对地址java做图片上传的代码 , 并在后面加上/bookpicture
File f = new File(root, this.getFileFileName());
//定义一个FILE文件 , 第一个参数是文件的路径,第二个是文件的名字
picture="." "\\" "bookpicture" "\\" this.getFileFileName();
//为PICTURE字符串赋值,/地址/文件名
System.out.println
("======picture=====" picture);
//从控制台输出Picture
OutputStream os = new FileOutputStream(f);
//第一个文件的输出流
byte[] buffer = new byte[1024];
//定义一个bufer的字符串,长度为1024
int len = 0;
while ((len = is.read(buffer))0) {
//如果从制定文件中读取到的信息为结束就继续循环
os.write(buffer, 0, len);
//将文件读出的内容写入到指定的文件中
}
java怎样上传图片(写个例子谢谢);我有一段上传图片的代码java做图片上传的代码,并且可以根据实际java做图片上传的代码,按月或按天等,生成存放图片的文件夹
首先在JSP上放一个FILE的标签这些我都不说了 , java做图片上传的代码你也一定明白,我直接把处理过程给你发过去
我把其中存到数据库中的内容删除了 , 你改一下就能用
/**
*
* 上传图片
* @param servlet
* @param request
* @param response
* @return
* @throws Exception
*/
//这里我是同步上传的,你随意
public synchronized String importPic(HttpServlet servlet, HttpServletRequest request,HttpServletResponse response) throws Exception {
SimpleDate()FormatformatDate()=newSimpleDate()Format("yyyyMM");
Date nowtime=new Date();
String formatnowtime=formatDate.format(nowtime);
Fileroot=newFile(request.getRealPath("/") "uploadfile/images/" formatnowtime "/"); //应保证在根目录中有此目录的存在如果没有,下面则上创建新的文件夹
if(!root.isDirectory())
{
System.out.println("创建新文件夹成功" formatnowtime);
root.mkdir();
}
int returnflag = 0;
SmartUpload mySmartUpload =new SmartUpload();
int file_size_max=1024000;
String ext="";
String url="uploadfile/images/" formatnowtime "/";
// 只允许上载此类文件
try{
// 初始化
mySmartUpload.initialize(servlet.getServletConfig(),request,response);
mySmartUpload.setAllowedFilesList("jpg,gif,bmp,jpeg,png,JPG");
//上载文件
mySmartUpload.upload();
} catch (Exception e){
response.sendRedirect()//返回页面
}
com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(0);
if (myFile.isMissing()){//没有选择图片做提示java做图片上传的代码!
returnflag = 3;
}else{
String myFileName=myFile.getFileName(); //取得上载的文件的文件名
ext= myFile.getFileExt();//取得后缀名
if(ext.equals("jpg")||ext.equals("gif")||ext.equals("bmp")||ext.equals("jpeg")||ext.equals("png")||ext.equals("JPG")){//jpeg,png不能上传!)
int file_size=myFile.getSize();//取得文件的大小
String saveurl="";
if(file_sizefile_size_max){
try{
//我上面说到,把操作数据库的代友删除了,这里就应该是判断 , 你的图片是不是已经存在了,存在要怎么处理,不存在要怎么处了,就是你的事了}
//更改文件名 , 取得当前上传时间的毫秒数值
Calendar calendar = Calendar.getInstance();
//String filename = String.valueOf(calendar.getTimeInMillis());
String did= contractBean.getMaxSeq("MULTIMEDIA_SEQ");
String filename = did;
String flag = "0";
String path = request.getRealPath("/") url;
String ename = myFile.getFileExt();
//.toLowerCase()转换大小写
saveurl=request.getRealPath("/") url;
saveurl =filename "." ext;//保存路径
myFile.saveAs(saveurl,mySmartUpload.SAVE_PHYSICAL);
//将图片信息插入到数据库中
// ------上传完成,开始生成缩略图-----
java.io.File file = new java.io.File(saveurl);//读入刚才上传的文件
String newurl=request.getRealPath("/") url filename "_min." ext;//新的缩略图保存地址
Image src = /uploads/allimg/240909/0205535934-0.jpgjavax.imageio.ImageIO.read(file);//构造Image对象
float tagsize=200;
int old_w=src.getWidth(null);
int old_h=src.getHeight(null);
int new_w=0;
int new_h=0;
int tempsize;
float tempdouble;
if(old_wold_h){
tempdouble=old_w/tagsize;
}else{
tempdouble=old_h/tagsize;
}
//new_w=Math.round(old_w/tempdouble);
//new_h=Math.round(old_h/tempdouble);//计算新图长宽
new_w=150;
new_h=110;//计算新图长宽
BufferedImage tag = new BufferedImage(new_w,new_h,BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(src,0,0,new_w,new_h,null);//绘制缩小后的图
FileOutputStream newimage=new FileOutputStream(newurl);//输出到文件流
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);
encoder.encode(tag);//近JPEG编码
newimage.close();
returnflag = 1;
}else{
returnflag = 0;
System.out.println("('上传文件大小不能超过" (file_size_max/1000) "K');");
}
}else{
returnflag = 2;
}
}
response.sendRedirect();
return "11";
}
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 = /uploads/allimg/240909/0205535934-0.jpgfi.getName();
if(pathSrc.trim().equals("")){
continue;
}
int start = pathSrc.lastIndexOf('\\');
String fileName = pathSrc.substring(start1);
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做图片上传的代码的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于javaweb实现图片上传、java做图片上传的代码的信息别忘了在本站进行查找喔 。

    推荐阅读