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

javahttp图片上传

发布时间: 2023-05-07 02:27:40

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实现图片上传至服务器并显示,如何做

给你段代码,是用来在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 怎么根据httpPost 和httpClient 等,传图片到服务器!

使用Apache提供的HttpClient组件可以实现。其实传图片就是用POST方式向服务器发送数据。

④ 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利用HttpURLConnection发送post请求上传文件

在页面里实现上传文件不是什么难事 写个form 加上enctype = multipart/form data 在写个接收的就可以了 没租裤什么难的 如果要用 HttpURLConnection来实现文件上传 还真有点搞头 : )

先写个servlet把接收到的 HTTP 信息保存在一个文件中 看一下 form 表单到底封装了什么样的信息

Java代码

public void doPost(HttpServletRequest request HttpServletResponse response)

throws ServletException IOException {

//获取输入流 是HTTP协议中的实体内容

ServletInputStream in=request getInputStream();

//缓冲区

byte buffer[]=new byte[ ];

FileOutputStream out=new FileOutputStream( d:\test log );

int len=sis read(buffer );

//把流里的信息循环读入到file log文件中

while( len!= ){

out write(buffer len);

len=in readLine(buffer );

}

out close();

in close();

}

来一个form表单

<form name= upform action= upload do method= POST

enctype= multipart/form data >

参数<input type= text name= username /><br/>

文件 <input type= file name= file /><br/>

文件 <input type= file name= file /><br/>

<input type= submit value= Submit />

<br />

</form>

假如我参数写的内容是hello word 然后二个文件是二个简单的txt文件梁誉 上传后test log里如下

Java代码

da e c

Content Disposition: form data; name= username

hello word

da e c

Content Disposition: form data; name= file ; filename= D:haha txt

Content Type: text/plain

haha

hahaha

da e c

Content Disposition: form data; name= file ; filename= D:huhu txt

Content Type: text/plain

messi

huhu

da e c

研究下规律发现有如下几点特征

第一行是 d b bc 作为分隔符 然后是 回车换行符 这个 d b bc 分隔符浏览器是随机生成的

第二行是Content Disposition: form data; name= file ; filename= D:huhu txt ;name=对应input的name值 filename对应要上传的文件名(包括路径在内)

第三行如果是文件就有Content Type: text/plain 这里上传的是txt文件所以是text/plain 如果上穿的是jpg图片的话就是image/jpg了 可以自己试试看看

然后就是回弊渣简车换行符

在下就是文件或参数的内容或值了 如 hello word

最后一行是 da e c 注意最后多了二个 ;

有了这些就可以使用HttpURLConnection来实现上传文件功能了

Java代码 public void upload(){

List<String> list = new ArrayList<String>(); //要上传的文件名 如 d:haha doc 你要实现自己的业务 我这里就是一个空list

try {

String BOUNDARY = d a d c ; // 定义数据分隔线

URL url = new URL( );

HttpURLConnection conn = (HttpURLConnection) url openConnection();

// 发送POST请求必须设置如下两行

conn setDoOutput(true);

conn setDoInput(true);

conn setUseCaches(false);

conn setRequestMethod( POST );

conn setRequestProperty( connection Keep Alive );

conn setRequestProperty( user agent Mozilla/ (patible; MSIE ; Windows NT ; SV ) );

conn setRequestProperty( Charsert UTF );

conn setRequestProperty( Content Type multipart/form data; boundary= + BOUNDARY);

OutputStream out = new DataOutputStream(conn getOutputStream());

byte[] end_data = ( + BOUNDARY + ) getBytes();// 定义最后数据分隔线

int leng = list size();

for(int i= ;i<leng;i++){

String fname = list get(i);

File file = new File(fname);

StringBuilder *** = new StringBuilder();

*** append( );

*** append(BOUNDARY);

*** append( );

*** append( Content Disposition: form data;name= file +i+ ;filename= + file getName() + );

*** append( Content Type:application/octet stream );

byte[] data = *** toString() getBytes();

out write(data);

DataInputStream in = new DataInputStream(new FileInputStream(file));

int bytes = ;

byte[] bufferOut = new byte[ ];

while ((bytes = in read(bufferOut)) != ) {

out write(bufferOut bytes);

}

out write( getBytes()); //多个文件时 二个文件之间加入这个

in close();

}

out write(end_data);

out flush();

out close();

// 定义BufferedReader输入流来读取URL的响应

BufferedReader reader = new BufferedReader(new InputStreamReader(conn getInputStream()));

String line = null;

while ((line = reader readLine()) != null) {

System out println(line);

}

} catch (Exception e) {

System out println( 发送POST请求出现异常! + e);

e printStackTrace();

}

lishixin/Article/program/Java/hx/201311/27114

⑥ java上传图片到远程服务器上,怎么解决呢

需要这样的一个包 jcifs-1.1.11
public static void forcdt(String dir){
InputStream in = null;
OutputStream out = null;
File localFile = new File(dir);
try{
//创建file类 传入本地文件路径
//获得本地文件的名字
String fileName = localFile.getName();
//将本地文件的名字和远程目录的名字拼接在一起
//确保上传后的文件于本地文件名字相同
SmbFile remoteFile = new SmbFile("smb://administrator:[email protected]/e$/aa/");
//创建读取缓冲流把本地的文件与程序连接在一起
in = new BufferedInputStream(new FileInputStream(localFile));
//创建一个写出缓冲流(注意jcifs-1.3.15.jar包 类名为Smb开头的类为控制远程共享计算机"io"包)
//将远程的文件路径传入SmbFileOutputStream中 并用 缓冲流套接
out = new BufferedOutputStream(new SmbFileOutputStream(remoteFile+"/"+fileName));
//创建中转字节数组
byte[] buffer = new byte[1024];
while(in.read(buffer)!=-1){//in对象的read方法返回-1为 文件以读取完毕
out.write(buffer);
buffer = new byte[1024];
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
//注意用完操作io对象的方法后关闭这些资源,走则 造成文件上传失败等问题。!
out.close();
in.close();
}catch(Exception e){
e.printStackTrace();}
}
}

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

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

⑧ 请教各位问题:java web客户端上传图片到服务器的D盘下,请问客户端怎么通过http访问图片

如果想让tomcat服务器访问指定磁盘 上的静态资源,可在tomcat/conf/server.xml中查找<Host></Host>,在标签中添加如下标签<Context path="/file" docBase="D:/img" reloadable="true"/>,再通过localhost:8080/file地址来访问路境内的文件:
如要访问名为d:/img/cat.png的图片,则localhost:8080/file/cat.png

⑨ java中图片上传到云服务器遇到的问题

可以亩戚使用java.net.HttpURLConnection模拟上传,,,,也可以使用老裤apache的HttpClient模拟POST上传侍耐简的~

⑩ java上传图片到服务器指定路径

privateFilemyFile;//文件
;//类型
privateStringmyFileFileName;//文件名
//。。。。getXXX()setXXX()方法

//输入流
InputStreamis=newFileInputStream(myFile);
//设定文件路径
StringphotoPath=ServletActionContext.getServletContext()
.getRealPath("/user/photo/");
FilefilePhotoPath=newFile(photoPath);
//判断这个路径是否存在,如果不存在创建这个路径
if(!filePhotoPath.isDirectory()){
filePhotoPath.mkdir();
}

Stringextension=FilenameUtils.getExtension(this
.getMyFileFileName());//后缀名比如jpg
Stringfilename=UUID.randomUUID().toString()+"."+extension;

//目标文件
Filetofile=newFile(photoPath,filename);
//输出流
OutputStreamos=newFileOutputStream(tofile);
byte[]buffer=newbyte[1024];
intlength=0;
while((length=is.read(buffer))>0){
os.write(buffer,0,length);
}
//关闭输入流
is.close();
//关闭输出流
os.close();

热点内容
c语言二码表 发布:2025-02-13 00:37:46 浏览:235
免费加密文件 发布:2025-02-13 00:35:00 浏览:176
菲亚特菲翔怎么区别配置 发布:2025-02-13 00:21:19 浏览:985
服务器好坏重点看什么 发布:2025-02-13 00:19:47 浏览:587
php把数据插入数据库 发布:2025-02-13 00:09:48 浏览:369
eclipse查看jar包源码 发布:2025-02-12 23:59:35 浏览:973
电脑主机服务器维修 发布:2025-02-12 23:59:26 浏览:302
sqlserver标识 发布:2025-02-12 23:51:33 浏览:463
安卓怎么玩地牢猎人 发布:2025-02-12 23:50:25 浏览:944
思乡脚本 发布:2025-02-12 23:43:32 浏览:440