2012-09-14 72 views
0

我有一段代碼可以幫助我將圖像保存在服務器上。我需要知道如何在div上顯示保存的圖像。使用JSP檢索和顯示來自服務器的圖像

JSP代碼:

<%String saveFile=""; 
String contentType = request.getContentType(); 
if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) { 
DataInputStream in = new DataInputStream(request.getInputStream()); 
int formDataLength = request.getContentLength(); 
byte dataBytes[] = new byte[formDataLength]; 
int byteRead = 0; 
int totalBytesRead = 0; 
while (totalBytesRead < formDataLength) { 
byteRead = in.read(dataBytes, totalBytesRead,formDataLength); 
totalBytesRead += byteRead; 
} 
String file = new String(dataBytes); 
saveFile = file.substring(file.indexOf("filename=\"") + 10); 
saveFile = saveFile.substring(0, saveFile.indexOf("\n")); 
saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\"")); 
int lastIndex = contentType.lastIndexOf("="); 
String boundary = contentType.substring(lastIndex + 1,contentType.length()); 
int pos; 
pos = file.indexOf("filename=\""); 
pos = file.indexOf("\n", pos) + 1; 
pos = file.indexOf("\n", pos) + 1; 
pos = file.indexOf("\n", pos) + 1; 
int boundaryLocation = file.indexOf(boundary, pos) - 4; 
int startPos = ((file.substring(0, pos)).getBytes()).length; 
int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length; 
saveFile="D:/../images/"+saveFile; 
File f = new File(saveFile); 
FileOutputStream fileOut = new FileOutputStream(f); 
fileOut.write(dataBytes, startPos, (endPos - startPos)); 
fileOut.flush(); 
fileOut.close(); 
}%> 
+1

使用Servlet而不是JSP.And是什麼問題? –

+0

當我瀏覽圖像並調用這個jsp頁面。圖像已成功保存在D:/../圖像文件夾中,但我不知道如何檢索該圖像並在html上顯示。 關於servlet。我並不清楚這一點。有沒有任何在服務器上保存圖像的例子? –

+0

您_will_需要一個servlet。檢查[例如,如何使用在響應中包含圖像的Servlet顯示JSP頁面(http://stackoverflow.com/questions/6347752))。 –

回答

0
fileName = new File("D:/../images/"+saveFile;).getName(); 

使用這個變量獲得的名稱,然後調用文件名中的IMG SRC。希望這可以幫助。

相關問題