当前位置:首页 » 文件管理 » java上传显示图片

java上传显示图片

发布时间: 2024-02-24 23:06:31

❶ 用java Web的jsp制作图片上传和显示如何实现

用jspSmartUpload组件来实现,用jsp+servlet在Servlet里实现的代码:

PrintWriter out = response.getWriter();
int count = 0;
// 实例化上传控件对象
SmartUpload su = new SmartUpload();
// 初始化操作
su.initialize(config, request, response);

// 设置上传文件最大字节数
su.setTotalMaxFileSize(100000);

//
try {
//禁止上传指定扩展名的文件
su.setDeniedFilesList("ext,bat,jsp");
} catch (SQLException e1) {
e1.printStackTrace();
}

try {
// 上传文件到服务器
su.upload();

File fileup = new File(request.getRealPath("upload"));
if(!fileup.exists()){
// 创建目录
fileup.mkdir();
}
// 处理多个文件的上传
for(int i = 0;i < su.getFiles().getCount();i++){
com.jspsmart.upload.File file = su.getFiles().getFile(i);
if(!file.isMissing()){ // 如果文件有效
// 保存文件到指定上传目录
file.saveAs("/upload/new."+file.getFileExt(), su.SAVE_VIRTUAL);
count = su.save("/upload");
}
}

} catch (SmartUploadException e) {

e.printStackTrace();
}
out.println(count +"file(s) uploaded");

如果你对这个上传组件不了解,最好是先去查查用法。。。

❷ java实现图片上传并显示

file inputstream outputstream ,基本上IO流章节实现,当然还有很多封装的jar包,网上去搜搜。另外,图片上传你还需一个web层

❸ java上传图片本地预览最好有例子

<divid="localImag">

<imgid="preview"alt="预览图片"runat="server"style="width:200px;height:65px"/>

</div>

<asp:FileUploadonkeydown="returnfalse"onkeyup="returnfalse"ID="FileUpload1"

runat="server"Width="300px"onchange="setImagePreview(this,localImag,preview,'200px','65px');"/>
///<summary>
///上传文件
///</summary>
///<paramname="MyFile"></param>
///<paramname="dirPath">文件存储路径(相对路径)</param>
///<paramname="errorMsg">错误信息</param>
///<returns>文件名</returns>
(FileUploadAttachFile,stringdirPath,outstringerrorMsg)
{
stringfileMsg=CheckUploadFile(AttachFile);
//如果返回信息不为""则返回错误信息
if(!"".Equals(fileMsg))
{
errorMsg=fileMsg;
return"";
}
//获取文件名称,包含后缀
stringFileName=AttachFile.FileName;
//获取文件扩展名
stringExtenName=System.IO.Path.GetExtension(FileName);
//将后缀名称大写
stringupExtenName=ExtenName.ToUpper();
//获取上传文件存储相路径
stringRelativePath=dirPath;
//获取上传文件存储绝对路径
stringSavePath=System.Web.HttpContext.Current.Server.MapPath(RelativePath);
//远程用户ip地址
stringipStr=System.Web.HttpContext.Current.Request.UserHostAddress;
//判断存放文件夹是否存在
if(!Directory.Exists(SavePath))
{
//创建存放文件夹
Directory.CreateDirectory(SavePath);
}
//拼接成上传文件保存名称
stringSaveFileName=ipStr+"_"+DateTime.Now.ToString("yyyyMMddHHmmss")+ExtenName;
//生成文件上传全路径
stringSaveFilePath=SavePath+"/"+SaveFileName;
//将excel文件上传至服务器路径下
AttachFile.SaveAs(SaveFilePath);
errorMsg="";
returnSaveFileName;
}
functionshowUploadImg(flag){
if(flag==1){
document.getElementById("img_upload").style.display='';
}
else{
document.getElementById("img_upload").style.display='none';
}
}
functionsetImagePreview(docObj,localImagId,imgObjPreview,width,height){
if(docObj.files&&docObj.files[0]){
//火狐下,直接设img属性
imgObjPreview.style.display='block';
imgObjPreview.style.width=width;
imgObjPreview.style.height=height;
//火狐7以上版本不能用上面的getAsDataURL()方式获取,需要一下方式
imgObjPreview.src=window.URL.createObjectURL(docObj.files[0]);
}
else{
//IE下,使用滤镜
docObj.select();
varimgSrc=document.selection.createRange().text;
//必须设置初始大小
localImagId.style.width=width;
localImagId.style.height=height;
//图片异常的捕捉,防止用户修改后缀来伪造图片
try{
localImagId.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
localImagId.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src=imgSrc;
}
catch(e){
alert("您上传的图片格式不正确,请重新选择!");
returnfalse;
}
imgObjPreview.style.display='none';
document.selection.empty();
}
returntrue;
}

❹ 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程序,就在页面上放图<img src='服务器域名/保存的文件路径名/文件名' />
如果是窗体程序,就要在显示界面上加入图形显示控件,放入图片文件的完整路径

❻ 我用java写了个上传图片的功能,上传后为什么只有重启tomcat后,图片才能显示呢

不能把文件传到项目的工作空间去了,应该传到tomcat对应的项目下才行.
比如我的tomcat装在c盘下的,那么在路径C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps下会有个和工作空间里项目一样名称的文件夹,得把文件传到这里.

❼ 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实现图片上传至服务器并显示,如何做希望要具体的代码实现

很简单。
可以手写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又做了封装,使用起来更傻瓜化,很容易掌握。

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

热点内容
频率计源码 发布:2024-09-08 07:40:26 浏览:778
奥迪a6哪个配置带后排加热 发布:2024-09-08 07:06:32 浏览:100
linux修改apache端口 发布:2024-09-08 07:05:49 浏览:208
有多少个不同的密码子 发布:2024-09-08 07:00:46 浏览:566
linux搭建mysql服务器配置 发布:2024-09-08 06:50:02 浏览:995
加上www不能访问 发布:2024-09-08 06:39:52 浏览:811
银行支付密码器怎么用 发布:2024-09-08 06:39:52 浏览:513
苹果手机清理浏览器缓存怎么清理缓存 发布:2024-09-08 06:31:32 浏览:554
云服务器的优点与缺点 发布:2024-09-08 06:30:34 浏览:734
上传下载赚钱 发布:2024-09-08 06:14:51 浏览:258