导航:首页 > 编程语言 > java图片如何上传

java图片如何上传

发布时间:2022-10-02 01:37:13

㈠ 请问用java 如何实现图片上传功能

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

㈡ java怎样上传图片(写个例子谢谢);

我有一段上传图片的代码,并且可以根据实际,按月或按天等,生成存放图片的文件夹
首先在JSP上放一个FILE的标签这些我都不说了,你也一定明白,我直接把处理过程给你发过去
我把其中存到数据库中的内容删除了,你改一下就能用
/**
*
* 上传图片
* @param servlet
* @param request
* @param response
* @return
* @throws Exception
*/

//这里我是同步上传的,你随意
public synchronized String importPic(HttpServlet servlet, HttpServletRequest request,HttpServletResponse response) throws Exception {
SimpleDate()Format formatDate() = new SimpleDate()Format("yyyyMM");
Date nowtime=new Date();
String formatnowtime=formatDate.format(nowtime);
File root = new File(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()){ //没有选择图片做提示!
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_size<file_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 = javax.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_w>old_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 图片上传

//1.初始化smartupload对象
SmartUpload su=new SmartUpload();
su.initialize(pageContext);

//2.定义上传文件类型
su.setAllowedFilesList("gif,jpg,doc,txt");
//3.不允许上传类型
su.setDeniedFilesList("jsp,asp,html,exe,bat");
//4.设置字符编码、
su.setCharset("UTF-8");
//5.设置的单个上传最大限制
su.setMaxFileSize(5*1024*1024);
//6.总共上传限制
su.setTotalMaxFileSize(20*1024*1024);
//7.上传
su.upload();
//su.getFiles().getCount() 获取上传数
File file=su.getFiles().getFile(0);
String filename=file.getFileName();
System.out.print(filename);
String filepath="upload\\";
filepath+=file.getFileName();
file.saveAs(filepath,SmartUpload.SAVE_VIRTUAL);

㈣ java实现上传图片功能

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

㈤ 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怎么上传图片

  1. 使用Commons-FileUpload 上传文件

  2. Struts 的文件上传

  3. jspSmartUpload上传文件

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

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

㈧ java图片上传方案

给你简单的描述一下:上传的图片保存在WebRoot下,在WebRoot下建立专门保存的文件夹,每上传一张图片数据保存图片的路径以及图片的一些其他信息,你说的读取直接查出路径,用<img src="路径">即可显示

㈨ 怎么用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图片上传处理

upload.jsp
<%@ page contentType="text/html; charset=gb2312" language="java" import="java.util.*,com.jspsmart.upload.*" %>
<html>
<head>
<title>上传文件 </title>

</head>
<body>
<form id="form1" name="msform" method="post" action="do_upload.jsp" enctype="multipart/form-data" onSubmit="return Check_Found(this);" target="iframe1">
<table width="50%" border="1" align="center">
<tr>
<td align="center"><input type="text" name="name" id="text1"></td>
</tr>
<tr>
<td align="center">产品说明:
<input type="file" name="file2" value=""/>
<iframe name="iframe1" style="display:none"> </iframe>
<input type="submit" name="Submit" value="上传图片" />
</td>
</tr>
</table>
</form>
</body>
</html>

do_upload.jsp
<%@ page contentType="text/html; charset=gb2312" language="java" import="java.util.*,com.jspsmart.upload.*" %>
<html>
<head>
<title>文件上传处理页面 </title>

</head>
<body>
<%
SmartUpload su=new SmartUpload();
su.initialize(pageContext);
su.upload();
String name;
int count=su.save("/upload",su.SAVE_VIRTUAL);
out.println(count+"个文件上传成功! <br>");
for(int i=0;i <su.getFiles().getCount();i++)
{
com.jspsmart.upload.File file=su.getFiles().getFile(i);
if(file.isMissing()) continue;
String files=file.getFileName();
out.print("<script>window.parent.document.text1.value='../upload/"+file.getFileName()+"';</script>");
out.print("<script>alert('上传成功!');</script>");
response.setHeader("Refresh","0;URL=addnewproce.jsp");
}
%>
</body>
</html>

还需要组件才行

阅读全文

与java图片如何上传相关的资料

热点内容
操作系统代码编译 浏览:481
程序员东北大学 浏览:426
编译忽略空字符 浏览:117
多店铺阿里云服务器教程 浏览:378
单片机求初值 浏览:420
安卓机如何在电脑备份图片 浏览:925
ca证书加密机价格 浏览:798
天干地支年份算法 浏览:796
程序员打造的视频 浏览:7
java和php通信 浏览:680
为什么黑程序员 浏览:163
程序员男生 浏览:456
戴尔文件夹内文件怎么置顶 浏览:582
云服务器6m网速 浏览:722
vivo手机中国联通服务器地址 浏览:862
工程总控编译失败 浏览:707
燕赵红枫app如何下载 浏览:867
php查杀软件 浏览:878
教育管理学pdf 浏览:547
服务器均衡怎么使用 浏览:626