當前位置:首頁 » 文件管理 » 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 02:38:43 瀏覽:624
rowphp 發布:2025-02-13 02:37:16 瀏覽:711
光遇安卓服周年傘在哪裡領取 發布:2025-02-13 02:22:18 瀏覽:674
寫mv腳本軟體 發布:2025-02-13 02:21:56 瀏覽:696
超內核源碼 發布:2025-02-13 02:12:54 瀏覽:444
趣粉腳本 發布:2025-02-13 02:11:23 瀏覽:952
壓縮的茶葉怎麼弄開 發布:2025-02-13 02:11:16 瀏覽:739
n1ftp伺服器 發布:2025-02-13 02:10:39 瀏覽:348
沒有卡沒有密碼怎麼辦啊 發布:2025-02-13 01:51:53 瀏覽:461
linux2個ftp伺服器 發布:2025-02-13 01:44:31 瀏覽:15