當前位置:首頁 » 文件傳輸 » java協作開發實現圖片上傳
擴展閱讀
webinf下怎麼引入js 2023-08-31 21:54:13
堡壘機怎麼打開web 2023-08-31 21:54:11

java協作開發實現圖片上傳

發布時間: 2022-10-04 07:15:27

① 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 中如何向伺服器上傳圖片

我們使用一些已有的組件幫助我們實現這種上傳功能。
常用的上傳組件:
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實現圖片上傳

下面這是servlet的內容:
package demo;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class DemoServlet extends HttpServlet {

private static final String UPLOAD_DIRECTORY = "upload";
private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB
private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
DiskFileItemFactory factory=new DiskFileItemFactory();
ServletFileUpload sfu=new ServletFileUpload(factory);
sfu.setHeaderEncoding("UTF-8");
sfu.setProgressListener(new ProgressListener() {

public void update(long pBytesRead, long pContentLength, int pItems) {
System.out.println("文件大小為:"+pContentLength+",當前已處理:"+pBytesRead);

}
});
//判斷提交上來的數據是否是上傳表單的數據
if(!ServletFileUpload.isMultipartContent(request)){
PrintWriter writer= response.getWriter();
writer.println("Error:表單必須包含 enctype=multipart/form-data");
writer.flush();
return;
}
factory.setSizeThreshold(MEMORY_THRESHOLD);
//設置臨時儲存目錄
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
//設置最大文件上傳值
sfu.setFileSizeMax(MAX_FILE_SIZE);
//設置最大請求值(包含文件和表單數據)
sfu.setSizeMax(MAX_REQUEST_SIZE);
String uploadpath=getServletContext().getRealPath("./")+ File.separator+UPLOAD_DIRECTORY;
File file=new File(uploadpath);
if(!file.exists()){
file.mkdir();
}

try {
List<FileItem> formItems = sfu.parseRequest(request);
if(formItems!=null&&formItems.size()>0){
for(FileItem item:formItems){
if(!item.isFormField()){
String fileName=new File(item.getName()).getName();
String filePath=uploadpath+File.separator+fileName;
File storeFile=new File(filePath);
System.out.println(filePath);
item.write(storeFile);
request.setAttribute("message", "文件上傳成功!");
}
}
}
} catch (Exception e) {
request.setAttribute("message", "錯誤信息:"+e.getMessage());
}
getServletContext().getRequestDispatcher("/demo.jsp").forward(request, response);
}

}

下面是jsp的內容,jsp放到webapp下,如果想放到WEB-INF下就把servlet里轉發的路徑改一下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="demo.do" enctype="multipart/form-data" method="post">
<input type="file" name="file1" />
<%
String message = (String) request.getAttribute("message");
%>
<%=message%>
<input type="submit" value="提交"/>
</form>
</body>
</html>
這段代碼可以實現普通的文件上傳,有大小限制,上傳普通的圖片肯定沒問題,別的一些小的文件也能傳

④ java怎樣實現圖片上傳功能

圖片不會那麼的保存到資料庫中。
而是把圖片放到文件系統,或者你指定的一個位置。
然後再資料庫中存放的為圖片的路徑

⑤ java實現上傳圖片功能

首先需要先要在資料庫中建立一個數據表格一遍存儲和查詢,在數據表格中的項中添加數據區和存儲路徑。數據區用來存儲圖片,在存儲時需要用到轉換功能,讓圖片轉換成數據流字元然後才能導入資料庫進行存儲,並且在輸入同時在同一語句中添加存儲路徑。
希望以上思路能讓你有點啟發

⑥ java怎樣編寫發送圖片的程序

首先,我們創建一個新的web工程,在工程的WebRoot目錄下新建一個upload文件夾,這樣當我們將該工程部署到伺服器上時,伺服器便也生成個upload文件夾,用來存放上傳的資源。

然後,在WebRoot目錄下新建一個jsp文件,主要實現的作用就是選擇上傳的文件,提交至servlet來進行處理

詳細代碼如下:一個form將文件信息通過post方式傳送到指定的servlet

<%@pagelanguage="java"import="java.util.*"pageEncoding="utf-8"%>
<%
Stringpath=request.getContextPath();
StringbasePath=
request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%>
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN"><html><head>
<base<%=basePath%>">
<title>MyJSP'upload.jsp'startingpage</title><metahttp-equiv="pragma"content="no-cache">
<metahttp-equiv="cache-control"content="no-cache"><metahttp-equiv="expires"content="0">
<metahttp-equiv="keywords"content="keyword1,keyword2,keyword3"><metahttp-equiv="description"content="Thisismypage"><!--
<linkrel="stylesheet"type="text/css">-->
</head>
<body>
<formaction="/upload/UpLoad"method="post"enctype="multipart/form-data">
請選擇上傳的圖片或文件:<inputtype="file"name="fileName"/><inputtype="submit"value="上傳"/>
</form>
</body>
</html>

可以看到,我們將數據提交到工程下的upload/UpLoad。 之後,我們就來編寫這個servlet——UpLoad.java

packageload;importjava.io.File;
importjava.io.IOException;importjava.io.PrintWriter;importjava.util.List;
importjavax.servlet.ServletContext;importjavax.servlet.ServletException;importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importmons.fileupload.FileItem;
importmons.fileupload.FileUploadException;importmons.fileupload.disk.DiskFileItemFactory;importmons.fileupload.servlet.ServletFileUpload;{@SuppressWarnings("unchecked")@Override
protectedvoidservice(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,IOException{req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
//為解析類提供配置信息
DiskFileItemFactoryfactory=newDiskFileItemFactory();
//創建解析類的實例
ServletFileUploadsfu=newServletFileUpload(factory);
//開始解析
sfu.setFileSizeMax(1024*400);
//每個表單域中數據會封裝到一個對應的FileItem對象上try{
List<FileItem>items=sfu.parseRequest(req);
//區分表單域
for(inti=0;i<items.size();i++){FileItemitem=items.get(i);
varcpro_psid="u2572954";varcpro_pswidth=966;varcpro_psheight=120;
//isFormField為true,表示這不是文件上傳表單域if(!item.isFormField()){
ServletContextsctx=getServletContext();
//獲得存放文件的物理路徑
//upload下的某個文件夾得到當前在線的用戶找到對應的文件夾
Stringpath=sctx.getRealPath("/upload");System.out.println(path);
//獲得文件名
StringfileName=item.getName();System.out.println(fileName);
//該方法在某些平台(操作系統),會返迴路徑+文件名
fileName=fileName.substring(fileName.lastIndexOf("/")+1);Filefile=newFile(path+"\"+fileName);if(!file.exists()){item.write(file);
//將上傳圖片的名字記錄到資料庫中
resp.sendRedirect("/upload/l");}}}
}catch(Exceptione){e.printStackTrace();}
}
}

因為已對 代碼做了詳細的注釋,所以相信大家也能基本上傳的這個過程。要注意的一點是解析實例空間大小的設置。我們希望上傳的文件不會是無限大,因此,設置

.setFileSizeMax(1024*400);

⑦ 請問用Java 如何實現圖片上傳功能

自己寫程序來上傳位元組流文件很難的,用SmartUpload.jar包吧,專門用於JSP上傳下載的,唯一缺點就是中文支持不太好,不過你可以改一下原程序的字元集就行了。上網搜,沒有找我!我給你發

⑧ 在一個java項目中,怎樣實現上傳圖片的功能

可以使用Apache的common-fileupload組件進行上傳。
當然也可以使用其他方式,如ftp上傳等,可以用Apache下的common-net工具包。
剩下的就是在servlet、spring等框架中如何使用這些上傳工具包。這些框架都有介面實現在那裡。調用就可以。

⑨ 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 web開發,上傳圖片並讀取

java web開發中,使用文件操作類來上傳圖片並讀取,如下代碼:

*@desc:圖片處理工具
*@author:bingye
*@createTime:2015-3-17下午04:25:32
*@version:v1.0
*/
publicclassImageUtil{

/**
*將圖片寫到客戶端
*@author:bingye
*@createTime:2015-3-17下午04:36:04
*@history:
*@paramimage
*@paramresponsevoid
*/
publicstaticvoidwriteImage(byte[]image,HttpServletResponseresponse){
if(image==null){
return;
}
byte[]buffer=newbyte[1024];
InputStreamis=null;
OutputStreamos=null;
try{
is=newByteArrayInputStream(image);
os=response.getOutputStream();
while(is.read(buffer)!=-1){
os.write(buffer);
os.flush();
}
}catch(IOExceptione){
e.printStackTrace();
}finally{
try{
if(is!=null){is.close();}
if(os!=null){os.close();}
}catch(IOExceptione){
e.printStackTrace();
}
}
}

/**
*獲取指定路勁圖片
*@author:bingye
*@createTime:2015-3-21上午10:50:44
*@paramfilePath
*@paramresponsevoid
*/
publicstaticvoidwriteImage(StringfilePath,HttpServletResponseresponse){
FileimageFile=newFile(filePath);
if(imageFile!=null&&imageFile.exists()){
byte[]buffer=newbyte[1024];
InputStreamis=null;
OutputStreamos=null;
try{
is=newFileInputStream(imageFile);
os=response.getOutputStream();
while(is.read(buffer)!=-1){
os.write(buffer);
os.flush();
}
}catch(FileNotFoundExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}finally{
try{
if(is!=null){is.close();}
if(os!=null){os.close();}
}catch(IOExceptione){
e.printStackTrace();
}
}
}
}

/**
*圖片上傳到文件夾
*@author:bingye
*@createTime:2015-3-20下午08:07:25
*@paramfile
*@paramsavePath
*@returnboolean
*/
(CommonsMultipartFilefile,StringsavePath){
if(file!=null&&!file.isEmpty()){
//獲取文件名稱
StringfileName=file.getOriginalFilename();
//獲取後綴名
StringsuffixName=fileName.substring(fileName.indexOf(".")+1);
//新名稱
StringnewFileName=System.currentTimeMillis()+"."+suffixName;
//新文件路勁
StringfilePath=savePath+newFileName;
//獲取存儲文件路徑
FilefileDir=newFile(savePath);
if(!fileDir.exists()){
//如果文件夾沒有:新建
fileDir.mkdirs();
}
FileOutputStreamfos=null;
try{
fos=newFileOutputStream(filePath);
fos.write(file.getBytes());
fos.flush();
returnResultUtil.success("UPLOAD_SUCCESS",URLEncoder.encode(newFileName,"utf-8"));
}catch(Exceptione){
e.printStackTrace();
returnResultUtil.fail("UPLOAD_ERROR");
}finally{
try{
if(fos!=null){
fos.close();
}
}catch(IOExceptione){
e.printStackTrace();
returnResultUtil.fail("UPLOAD_ERROR");
}
}
}
returnResultUtil.fail("UPLOAD_ERROR");
}}