我正在尝试显示图像抛出jsp。图像存储在本地路径中,所以我编写了一个servlet get方法来检索图像,并在image标签的src属性中给出servlet名称和图像路径作为servlet的参数,这是我的代码,
public class FileServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final int DEFAULT_BUFFER_SIZE = 10240; // 10KB.
private String filePath;
public void init() throws ServletException {
this.filePath = "/files";
}
protected final void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("In do get");
// Get requested file by path info.
String requestedFile = request.getPathInfo();
// Check if file is actually supplied to the request URI.
if (requestedFile == null) {
// Do your thing if the file is not supplied to the request URI.
// Throw an exception, or send 404, or show default/warning page, or just ignore it.
response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
return;
}
// Decode the file name (might contain spaces and on) and prepare file object.
File file = new File(filePath, URLDecoder.decode(requestedFile, "UTF-8"));
// Check if file actually exists in filesystem.
if (!file.exists()) {
// Do your thing if the file appears to be non-existing.
// Throw an exception, or send 404, or show default/warning page, or just ignore it.
response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
return;
}
// Get content type by filename.
String contentType = getServletContext().getMimeType(file.getName());
// If content type is unknown, then set the default value.
// For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
// To add new content types, add new mime-mapping entry in web.xml.
if (contentType == null) {
contentType = "application/octet-stream";
}
// Init servlet response.
response.reset();
response.setBufferSize(DEFAULT_BUFFER_SIZE);
response.setContentType(contentType);
response.setHeader("Content-Length", String.valueOf(file.length()));
response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
// Prepare streams.
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
// Open streams.
input = new BufferedInputStream(new FileInputStream(file), DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);
// Write file contents to response.
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
} finally {
// Gently close streams.
close(output);
close(input);
}
}
protected final void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("In do post");
}
private static void close(Closeable resource) {
if (resource != null) {
try {
resource.close();
} catch (IOException e) {
// Do your thing with the exception. Print it, log it or mail it.
e.printStackTrace();
}
}
}
在web.xml中,servlet条目如下,
<servlet>
<description>
</description>
<display-name>FileServlet</display-name>
<servlet-name>FileServlet</servlet-name>
<servlet-class>com.mypackage.FileServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FileServlet</servlet-name>
<url-pattern>/file/*</url-pattern>
</servlet-mapping>
在Jsp中我有img标签如下,
<img alt="Image" src="file/D:/uploads/img14.jsp" width="160" height="160" class="img-thumbnail">
我认为我在img标签的src属性中犯了错误,任何人都可以告诉我这是我犯的错误。
答案 0 :(得分:1)
看起来你误解了BalusC的帖子:FileServlet。在这种情况下,您将在磁盘中有一个基本路径来为您的文件提供服务(在服务器中的Web应用程序文件夹路径的外部),然后您的URL中使用的路径将用于搜索内部这个基本路径。请注意BalusC的示例如何调用资源:
<a href="file/foo.exe">download foo.exe</a>
其中:
file 是Servlet的URL模式。在您的web.xml配置中注明:
<servlet-mapping>
<servlet-name>FileServlet</servlet-name>
<url-pattern>/file/*</url-pattern>
</servlet-mapping>
URL /foo.exe 的其余部分是服务器硬盘中文件的位置。使用HttpServletRequest.html#getPathInfo
这部分代码注明了这一点(评论是我的):
public void init() throws ServletException {
this.filePath = "/files";
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Get the file path from the URL.
String requestedFile = request.getPathInfo();
//...
//using filePath attribute in servletclass as the base path
//to lookup for the files, using the requestedFile
//path to seek for the existance of the file (by name)
//in your server
//decoding the name in case of GET request encoding such as
//%2F => /
File file = new File(filePath, URLDecoder.decode(requestedFile, "UTF-8"));
//...
}
然后,当有这样的请求时(在您的视图中使用HTML代码):
<img src="files/img/myimage.png" />
您必须确保服务器中存在该文件:
- / <-- root
- /files <-- this is the base file path set in init method in your servlet
- /img
- myimage.png
更多信息:
答案 1 :(得分:0)
您犯的错误是尝试将JSP页面作为图像资源调用。 JSP本身只是一个文本文件。您需要使用URL来替换文件的路径到服务器上的页面,该服务器将编译/提供JSP页面的结果,即图像。如果它位于本地服务器上,则网址通常会显示为http://localhost:<port>/.../img14.jsp
。
答案 2 :(得分:0)
img标签的src属性应该像这样向servlet发送请求。 src =“$ {pageContext.request.contextPath} /FileServlet/getImage?path=D:\offline_registration\11022017\unzip\a89a89e9-5de2-4bb2-9225-e465bb5705b1.jpeg”
此处路径变量包含来自本地系统的图像路径。
答案 3 :(得分:-1)
我尝试了下面的代码,它在servlet和java中都运行良好。如果使用下面的代码将图像转换为servlet中的字节,则在会话属性中设置转换后的字节代码并将其转换为jsp。
注意:它可以显示任何格式的图片
package Jx_Test;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.apache.commons.codec.binary.Base64;
public class Imag {
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
// TODO Auto-generated method stub
File file = new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\Desert.jpg");
FileInputStream fis = new FileInputStream(file);
//create FileInputStream which obtains input bytes from a file in a file system
//FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader.
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
try {
for (int readNum; (readNum = fis.read(buf)) != -1;) {
//Writes to this byte array output stream
bos.write(buf, 0, readNum);
System.out.println("read " + readNum + " bytes,");
}
} catch (IOException ex) {
// Logger.getLogger(ConvertImage.class.getName()).log(Level.SEVERE, null, ex);
}
byte[] bytes = bos.toByteArray();
byte[] encodeBase64 = Base64.encodeBase64(bytes);
String base64Encoded = new String(encodeBase64, "UTF-8");
System.out.println(base64Encoded);
}
}
//Jsp
<img src="data:image/jpeg;base64,<%=base64Encoded%>"/>