當前位置:首頁 » 文件管理 » java上傳顯示圖片

java上傳顯示圖片

發布時間: 2024-02-24 23:06:31

❶ 用java Web的jsp製作圖片上傳和顯示如何實現

用jspSmartUpload組件來實現,用jsp+servlet在Servlet里實現的代碼:

PrintWriter out = response.getWriter();
int count = 0;
// 實例化上傳控制項對象
SmartUpload su = new SmartUpload();
// 初始化操作
su.initialize(config, request, response);

// 設置上傳文件最大位元組數
su.setTotalMaxFileSize(100000);

//
try {
//禁止上傳指定擴展名的文件
su.setDeniedFilesList("ext,bat,jsp");
} catch (SQLException e1) {
e1.printStackTrace();
}

try {
// 上傳文件到伺服器
su.upload();

File fileup = new File(request.getRealPath("upload"));
if(!fileup.exists()){
// 創建目錄
fileup.mkdir();
}
// 處理多個文件的上傳
for(int i = 0;i < su.getFiles().getCount();i++){
com.jspsmart.upload.File file = su.getFiles().getFile(i);
if(!file.isMissing()){ // 如果文件有效
// 保存文件到指定上傳目錄
file.saveAs("/upload/new."+file.getFileExt(), su.SAVE_VIRTUAL);
count = su.save("/upload");
}
}

} catch (SmartUploadException e) {

e.printStackTrace();
}
out.println(count +"file(s) uploaded");

如果你對這個上傳組件不了解,最好是先去查查用法。。。

❷ java實現圖片上傳並顯示

file inputstream outputstream ,基本上IO流章節實現,當然還有很多封裝的jar包,網上去搜搜。另外,圖片上傳你還需一個web層

❸ java上傳圖片本地預覽最好有例子

<divid="localImag">

<imgid="preview"alt="預覽圖片"runat="server"style="width:200px;height:65px"/>

</div>

<asp:FileUploadonkeydown="returnfalse"onkeyup="returnfalse"ID="FileUpload1"

runat="server"Width="300px"onchange="setImagePreview(this,localImag,preview,'200px','65px');"/>
///<summary>
///上傳文件
///</summary>
///<paramname="MyFile"></param>
///<paramname="dirPath">文件存儲路徑(相對路徑)</param>
///<paramname="errorMsg">錯誤信息</param>
///<returns>文件名</returns>
(FileUploadAttachFile,stringdirPath,outstringerrorMsg)
{
stringfileMsg=CheckUploadFile(AttachFile);
//如果返回信息不為""則返回錯誤信息
if(!"".Equals(fileMsg))
{
errorMsg=fileMsg;
return"";
}
//獲取文件名稱,包含後綴
stringFileName=AttachFile.FileName;
//獲取文件擴展名
stringExtenName=System.IO.Path.GetExtension(FileName);
//將後綴名稱大寫
stringupExtenName=ExtenName.ToUpper();
//獲取上傳文件存儲相路徑
stringRelativePath=dirPath;
//獲取上傳文件存儲絕對路徑
stringSavePath=System.Web.HttpContext.Current.Server.MapPath(RelativePath);
//遠程用戶ip地址
stringipStr=System.Web.HttpContext.Current.Request.UserHostAddress;
//判斷存放文件夾是否存在
if(!Directory.Exists(SavePath))
{
//創建存放文件夾
Directory.CreateDirectory(SavePath);
}
//拼接成上傳文件保存名稱
stringSaveFileName=ipStr+"_"+DateTime.Now.ToString("yyyyMMddHHmmss")+ExtenName;
//生成文件上傳全路徑
stringSaveFilePath=SavePath+"/"+SaveFileName;
//將excel文件上傳至伺服器路徑下
AttachFile.SaveAs(SaveFilePath);
errorMsg="";
returnSaveFileName;
}
functionshowUploadImg(flag){
if(flag==1){
document.getElementById("img_upload").style.display='';
}
else{
document.getElementById("img_upload").style.display='none';
}
}
functionsetImagePreview(docObj,localImagId,imgObjPreview,width,height){
if(docObj.files&&docObj.files[0]){
//火狐下,直接設img屬性
imgObjPreview.style.display='block';
imgObjPreview.style.width=width;
imgObjPreview.style.height=height;
//火狐7以上版本不能用上面的getAsDataURL()方式獲取,需要一下方式
imgObjPreview.src=window.URL.createObjectURL(docObj.files[0]);
}
else{
//IE下,使用濾鏡
docObj.select();
varimgSrc=document.selection.createRange().text;
//必須設置初始大小
localImagId.style.width=width;
localImagId.style.height=height;
//圖片異常的捕捉,防止用戶修改後綴來偽造圖片
try{
localImagId.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
localImagId.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src=imgSrc;
}
catch(e){
alert("您上傳的圖片格式不正確,請重新選擇!");
returnfalse;
}
imgObjPreview.style.display='none';
document.selection.empty();
}
returntrue;
}

❹ 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程序,就在頁面上放圖<img src='伺服器域名/保存的文件路徑名/文件名' />
如果是窗體程序,就要在顯示界面上加入圖形顯示控制項,放入圖片文件的完整路徑

❻ 我用java寫了個上傳圖片的功能,上傳後為什麼只有重啟tomcat後,圖片才能顯示呢

不能把文件傳到項目的工作空間去了,應該傳到tomcat對應的項目下才行.
比如我的tomcat裝在c盤下的,那麼在路徑C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps下會有個和工作空間里項目一樣名稱的文件夾,得把文件傳到這里.

❼ 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實現圖片上傳至伺服器並顯示,如何做希望要具體的代碼實現

很簡單。
可以手寫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又做了封裝,使用起來更傻瓜化,很容易掌握。

-----------------------------
以上回答,如有不明白可以聯系我。

熱點內容
羊創意腳本 發布:2024-07-27 09:29:30 瀏覽:894
榮耀v20升級存儲 發布:2024-07-27 09:20:19 瀏覽:485
安卓用什麼和電腦傳圖片 發布:2024-07-27 09:02:07 瀏覽:288
存儲過程就是 發布:2024-07-27 08:56:51 瀏覽:131
c語言高級試題 發布:2024-07-27 08:48:30 瀏覽:282
ip伺服器世界上有幾台 發布:2024-07-27 08:46:18 瀏覽:394
金立手機怎麼清理緩存 發布:2024-07-27 08:38:50 瀏覽:311
iphone文件夾不顯示 發布:2024-07-27 08:18:05 瀏覽:774
y510p固態硬碟做緩存 發布:2024-07-27 07:59:34 瀏覽:128
奶塊為什麼進伺服器會排隊 發布:2024-07-27 07:57:15 瀏覽:691