導航:首頁 > IDC知識 > java圖片上傳伺服器

java圖片上傳伺服器

發布時間:2020-11-07 20:47:48

1、java通過圖片的名字上傳到伺服器的方法

提交頁面表單
<form action="up.jsp" enctype="multipart/form-data" method="post">
<input type="file" name="file">
<input type="submit" value="確定">
</form>
上傳頁面內容up.jsp
<%@page import="java.io.FileWriter"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
import="java.io.*"
pageEncoding="UTF-8"%>
<%

2、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();}
}
}

3、java怎麼實現上傳文件到伺服器

common-fileupload是jakarta項目組開發的一個功能很強大的上傳文件組件

下面先介紹上傳文件到伺服器(多文件上傳):

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

import java.util.*;

import java.util.regex.*;

import org.apache.commons.fileupload.*;


public class upload extends HttpServlet {

private static final String CONTENT_TYPE = "text/html; charset=GB2312";

//Process the HTTP Post request

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setContentType(CONTENT_TYPE);

PrintWriter out=response.getWriter();

try {

DiskFileUpload fu = new DiskFileUpload();

 // 設置允許用戶上傳文件大小,單位:位元組,這里設為2m

 fu.setSizeMax(2*1024*1024);

 // 設置最多隻允許在內存中存儲的數據,單位:位元組

 fu.setSizeThreshold(4096);

 // 設置一旦文件大小超過getSizeThreshold()的值時數據存放在硬碟的目錄

 fu.setRepositoryPath("c://windows//temp");

 //開始讀取上傳信息

 List fileItems = fu.parseRequest(request);

 // 依次處理每個上傳的文件

 Iterator iter = fileItems.iterator();

//正則匹配,過濾路徑取文件名

 String regExp=".+////(.+)$";

//過濾掉的文件類型

String[] errorType={".exe",".com",".cgi",".asp"};

 Pattern p = Pattern.compile(regExp);

 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;

 Matcher m = p.matcher(name);

 boolean result = m.find();

 if (result){

 for (int temp=0;temp<ERRORTYPE.LENGTH;TEMP++){

 if (m.group(1).endsWith(errorType[temp])){

 throw new IOException(name+": wrong type");

 }

 }

 try{

//保存上傳的文件到指定的目錄

//在下文中上傳文件至資料庫時,將對這里改寫

 item.write(new File("d://" + m.group(1)));

out.print(name+"  "+size+"");

 }

 catch(Exception e){

 out.println(e);

 }

}

 else

 {

 throw new IOException("fail to upload");

 }

 }

 }

}

 catch (IOException e){

 out.println(e);

 }

 catch (FileUploadException e){

out.println(e);

 }

 

}

}

現在介紹上傳文件到伺服器,下面只寫出相關代碼:

以sql2000為例,表結構如下:

欄位名:name  filecode

類型: varchar image

資料庫插入代碼為:PreparedStatement pstmt=conn.prepareStatement("insert into test values(?,?)");

代碼如下:

。。。。。。

try{

這段代碼如果不去掉,將一同寫入到伺服器中

//item.write(new File("d://" + m.group(1)));

 

int byteread=0;

//讀取輸入流,也就是上傳的文件內容

InputStream inStream=item.getInputStream();  

pstmt.setString(1,m.group(1));

pstmt.setBinaryStream(2,inStream,(int)size);

pstmt.executeUpdate();

inStream.close();

out.println(name+"  "+size+" ");

}

。。。。。。

這樣就實現了上傳文件至資料庫

4、java如何實現上傳圖片到伺服器,並預覽圖片

預覽,不能簡單的用<img>,然後把地址賦給src的,會出現瀏覽器不兼容問題
用css濾鏡,像下面
document.getElementById("previewImg").style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src='" + o.value + "')";
至於如何上傳,struts2很方便的

5、java 如何只通過後台把本地的圖片上傳的伺服器上去

import java.io.*;
public class CopyIMG{
    public static void main(String[] args)throws Exception{
        File file = new File("C:\xx.jpg");
        if(!file.exists())
            throw new RuntimeException("文件不存在..");
        FileInputStream fis = new FileInputStream(file);
        byte[] b = new byte[1024];
        int len = 0;
        FileOutputStream fos = new FileOutStream("要保存的伺服器路徑");
        while((len=is.read(b))!=-1){
            fos.write(b,0,len);
        }
        fos.close();
        fis.close();
    }
}

6、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);
}

7、java上傳圖片到伺服器指定路徑

        private File myFile; //文件
private String myFileContentType; //類型
private String myFileFileName;    //文件名
//。。。。getXXX() setXXX()方法

//輸入流
InputStream is = new FileInputStream(myFile);
//設定文件路徑
String photoPath = ServletActionContext.getServletContext()
.getRealPath("/user/photo/");
File filePhotoPath = new File(photoPath);
//判斷這個路徑是否存在,如果不存在創建這個路徑
if (!filePhotoPath.isDirectory()) {
filePhotoPath.mkdir();
}

String extension = FilenameUtils.getExtension(this
.getMyFileFileName());   //後綴名 比如jpg
String filename = UUID.randomUUID().toString() + "." + extension;

// 目標文件
File tofile = new File(photoPath, filename);
// 輸出流
OutputStream os = new FileOutputStream(tofile);
byte[] buffer = new byte[1024];
int length = 0;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
// 關閉輸入流
is.close();
// 關閉輸出流
os.close();

8、java中怎麼將本地圖片上傳到伺服器上

伺服器端,做一個FTP,客戶端使用APACHE的FTP組件上傳。。。。。。。



伺服器端實現HTTP的POST接收,,,,,客戶端使用httpclient組件post上去

與java圖片上傳伺服器相關的知識