導航:首頁 > 編程語言 > 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圖片相關的資料

熱點內容
哪個app有自學的專業 瀏覽:692
蘋果11給QQ加密在哪裡設置 瀏覽:581
安卓全家桶怎麼用 瀏覽:219
艾隆納亞伺服器什麼級別 瀏覽:321
360linux版本 瀏覽:185
程序員怎麼改變手機號碼 瀏覽:696
網站伺服器續費怎麼續費 瀏覽:534
cad等距線段快捷鍵命令 瀏覽:420
冰箱app和黑域哪個好用 瀏覽:223
鶴崗買房軟體app哪個最靠譜 瀏覽:719
python模擬登錄京東 瀏覽:282
irc命令 瀏覽:273
清空cisco交換機命令 瀏覽:760
地面波收費加密台搜不到了 瀏覽:283
小米更新一直顯示加密中 瀏覽:601
jsgzip解壓縮 瀏覽:428
邏輯電路設計怎麼編譯 瀏覽:758
捏手機解壓視頻 瀏覽:498
電腦解鎖加密分區 瀏覽:493
響應文本加密怎麼破解 瀏覽:381