导航:首页 > 编程语言 > javapost图片

javapost图片

发布时间:2023-07-05 10:07:00

java获取远程图片,获取不全

用这个吧,这个方法是我从apache commons中扒下来的,没有问题的,记得采纳啊

/**
*从URL抓取一个文件写到本地<br>
*这个方法摘自<ahref="http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html">org.apache.commons.io.FileUtils.URLToFile(URLsource,Filedestination)</a>
*@paramsource
*@paramdestination
*@throwsIOException
*/
publicstaticvoidFileFromURL(URLsource,Filedestination)throwsIOException{

InputStreaminput=null;
FileOutputStreamoutput=null;
byte[]族虚buffer=newbyte[1024];

input=source.openStream();

if(destination.exists()){
if(destination.isDirectory()){
thrownewIOException("File'"姿穗并+destination
+"'existsbutisadirectory");
}
if(destination.canWrite()==false){
thrownewIOException("File'"+destination
+"'cannotbewrittento");
}
}else{
Fileparent迹迹=destination.getParentFile();
if(parent!=null){
if(!parent.mkdirs()&&!parent.isDirectory()){
thrownewIOException("Directory'"+parent
+"'couldnotbecreated");
}
}
}

output=newFileOutputStream(destination,true);

intn=0;
while(-1!=(n=input.read(buffer))){
output.write(buffer,0,n);
}
output.close();
input.close();
}

㈡ 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完成图片多张批量上传的功能,还有就是后台的应该怎么处理上传的照片。

环境准备

1. 下载并安装Tomcat(已经有很多关于Tomcat安装以及使用的文章,在这里不再介绍);

2. 下载File upload的jar包commons-fileupload-1.0-beta-1.jar,并将该文件拷贝到{$TOMCAT}/common/lib目录下(其中{$TOMCAT}为Tomcat的安装目录);

3. 由于Fileupload子项目同时要用到另外一个项目commons-Beanutils,所以必须下载Beanutils,并将解压后的文件commons-beanutils.jar拷贝到{$TOMCAT}/common/lib目录下。

开发文件上传页面

文件上传的界面如图1所示。为了增加效率我们设计了三个文件域,同时上传三个文件。
图1 文件上传界面

页面的HTML代码如下:

<html>
<head>
<title>文件上传演示</title>
</head>
<body bgcolor=“#FFFFFF”text=“#000000” leftmargin=“0”topmargin=“40”marginwidth=“0” marginheight=“0”>
<center>
<h1>文件上传演示</h1>
<form name=“uploadform”method=“POST” action=“save.jsp”ENCTYPE=“multipart/form-data”>
<table border=“1”width=“450”cellpadding=“4” cellspacing=“2”bordercolor=“#9BD7FF”>
<tr><td width=“100%”colspan=“2”>
文件1:<input name=“file1”size=“40”type=“file”>
</td></tr>
<tr><td width=“100%”colspan=“2”>
文件2:<input name=“file2”size=“40”type=“file”>
</td></tr>
<tr><td width=“100%”colspan=“2”>
文件3:<input name=“file3”size=“40”type=“file”>
</td></tr>
</table>
<br/><br/>
<table>
<tr><td align=“center”><input name=“upload” type=“submit”value=“开始上传”/></td></tr>
</table>
</form>
</center>
</body>
</html>

代码中要特别注意的是黑体处。必须保证表单的ENCTYPE属性值为multipart/form-data,这样浏览器才能正确执行上传文件的操作。

处理上传文件信息

由于本文主要是讲述如何使用Commons-fileupload,所以为了便于修改、调试,上传文件的保存使用一个JSP文件来进行处理。我们将浏览器上传来的所有文件保存在一个指定目录下并在页面上显示所有上传文件的详细信息。保存页面处理结果见图2所示。
图2 保存页面

下面来看看save.jsp的代码:

<%
/**
* 演示文件上传的处理
* @author <a href=“mailto:[email protected]”>Winter Lau</a>
* @version $Id: save.jsp,v 1.00 2003/03/01 10:10:15
*/
%>
<%@ page language=“java”contentType=“text/html;charset=GBK”%>
<%@ page import=“java.util.*”%>
<%@ page import=“org.apache.commons.fileupload.*”%>
<html>
<head>
<title>保存上传文件</title>
</head>
<%
String msg = “”;
FileUpload fu = new FileUpload();
// 设置允许用户上传文件大小,单位:字节
fu.setSizeMax(10000000);
// maximum size that will be stored in memory?
// 设置最多只允许在内存中存储的数据,单位:字节
fu.setSizeThreshold(4096);
// 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录
fu.setRepositoryPath(“C:\\TEMP”);
//开始读取上传信息
List fileItems = fu.parseRequest(request);
%>
<body bgcolor=“#FFFFFF”text=“#000000” leftmargin=“0”topmargin=“40”marginwidth=“0” marginheight=“0”>
<font size=“6”color=“blue”>文件列表:</font>
<center>
<table cellpadding=0 cellspacing=1 border=1 width=“100%”>
<tr>
<td bgcolor=“#008080”>文件名</td>
<td bgcolor=“#008080”>大小</td>
</tr>
<%
// 依次处理每个上传的文件
Iterator iter = fileItems.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
//忽略其他不是文件域的所有表单信息
if (!item.isFormField()) {
String name = item.getName();
long size = item.getSize();
if((name==null||name.equals(“”)) && size==0)
continue;
%>
<tr>
<td><%=item.getName()%></td>
<td><%=item.getSize()%></td>
</tr>
<%
//保存上传的文件到指定的目录
name = name.replace(‘:’,‘_’);
name = name.replace(‘\\’,‘_’);
item.write(“F:\\”+ name);
}
}
%>
</table>

<br/><br/>
<a href=“upload.html”>返回上传页面</a>
</center>
</body>
</html>

在这个文件中需要注意的是FileUpload对象的一些参数值的意义,如下面代码所示的三个参数sizeMax、sizeThreshold、repositoryPath:

FileUpload fu = new FileUpload();
// 设置允许用户上传文件大小,单位:字节
fu.setSizeMax(10000000);
// maximum size that will be stored in memory?
// 设置最多只允许在内存中存储的数据,单位:字节
fu.setSizeThreshold(4096);
// 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录
fu.setRepositoryPath(“C:\\TEMP”);

这3个参数的意义分别为:

SizeMax 用来设置上传文件大小的最大值,一旦用户上传的文件大小超过该值时将会抛出一个FileUploadException异常,提示文件太大;

SizeThreshold 设置内存中缓冲区的大小,一旦文件的大小超过该值的时候,程序会自动将其它数据存放在repositoryPath指定的目录下作为缓冲。合理设置该参数的值可以保证服务器稳定高效的运行;

RepositoryPath 指定缓冲区目录。

使用注意事项
从实际应用的结果来看该模块能够稳定高效的工作。其中参数SizeThreshold的值至关重要,设置太大会占用过多的内存,设置太小会频繁使用硬盘作为缓冲以致牺牲性能。因此,设置该值时要根据用户上传文件大小分布情况来设定。例如大部分文件大小集中在100KB左右,则可以使用100KB作为该参数的值,当然了再大就不合适了。使用commons-fileupload来处理HTTP文件上传的功能模块很小,但是值得研究的东西很多。

㈣ 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中判断URL地址的图片是否有效

下面给你分享一个小工具类,可以帮到你

在上传图片的时候会生成一个图片地址链接,把这个链接调用这个工具类进行判断,如果返回200,则图片上传成功,返回其他则图片地址有误,或者上传失败。

㈥ 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

阅读全文

与javapost图片相关的资料

热点内容
如何将文件夹的内容发到微信 浏览:892
安卓手机emoji扁平怎么办 浏览:208
欧版三星s20怎么升级安卓11 浏览:104
我的世界服务器如何拉黑房子 浏览:480
linux服务器网络设置 浏览:106
在线编译代码怎么做 浏览:205
社会研究方法教程pdf 浏览:696
cad修改服务器地址 浏览:788
新手服务器装什么系统好 浏览:128
androidxmlui 浏览:713
星辰之恋在哪个app播 浏览:465
手机卡服务器出错误是怎么回事 浏览:536
cg编译器怎么设置 浏览:418
单片机教学视频哪个好 浏览:598
编译器错误了怎么办 浏览:77
看摩托车用什么app好 浏览:405
pdf转换excel在线转换 浏览:361
php多客服 浏览:746
语言编译程序如何分类 浏览:377
pdf下载哪个 浏览:77