3 回答

TA貢獻1834條經驗 獲得超8個贊
您的 src 不應是服務器中文件的位置,源應該是將為您的資源提供服務的 http 鏈接。
您可以將 apache 配置為將 URL 映射到特定目錄中的資源,然后在 src 屬性中提及映射的 URL + 文件名
或者您可以創建一個控制器,它從特定位置獲取資源并將其作為字節流返回,并在 src 屬性中設置指向您的控制器的鏈接+文件名

TA貢獻1839條經驗 獲得超15個贊
我終于設法顯示圖像。如果有其他人試圖做同樣的事情,我想列出我采取的步驟。僅供參考,我使用的是 Tomcat 和 MySQL 數據庫。
確保您的圖像目錄存在于您的系統上并向其中添加圖像。
創建一個名為的新類
FileServlet
并將以下代碼應用到其中。
@WebServlet("/images/*")
public class FileServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException
{
String filename = URLDecoder.decode(request.getPathInfo().substring(1), "UTF-8");
File file = new File("C:\\your\\local\\image\\directory", filename);
response.setHeader("Content-Type", getServletContext().getMimeType(filename));
response.setHeader("Content-Length", String.valueOf(file.length()));
response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");
Files.copy(file.toPath(), response.getOutputStream());
}
}
現在轉到您的主類并應用一個名為@ServletComponentScan. 你的主類現在應該是這樣的:
@SpringBootApplication
@ServletComponentScan
public class WebApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(WebApplication.class);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(WebApplication.class, args);
}
}
在您的 .jsp 文件中,將此行添加到您想要顯示圖像的任何位置:
<img src="http://localhost:8080/images${YOUR_PASSED_OBJECT.RELATIVE_IMG_PATH_VARIABLE}">
重建您的 Web 應用程序并轉到localhost:PORT/images/YOUR_FILE_NAME.EXTENSION
如果您有任何問題,請隨時對此答案發表評論,我會根據需要進行更新。

TA貢獻1830條經驗 獲得超9個贊
假設您有 Apache tomcat 服務器。您將必須更新 server.xml 文件。添加
<Context??docBase="C:\your\physical\path"?path="/path/for/http/url"?/>
里面的<Host></Host>
標簽。這樣做,您可以訪問保存在其中的任何文件
“C:\你的\物理\路徑”
在 URL 的幫助下從您的 Web 應用程序:
“?http://yourdomain/?path/for/http/url?/somefile.someextension”
添加回答
舉報