2017-06-12 64 views
-1

我想讓我的jsp從本地機讀取圖像文件並將其傳遞給我的java類。可能嗎??或者它只能用java Servlet完成?使用java類從jsp讀取文件輸入

<form method="post" action="TestController" encType="multipart/form-data"> 
<table> 
<tr> 
<td><input type="file" name="UPLOAD" onchange="readURL(this);" style="width:150px;" /></td> 
<td><input type="image" id="img" src="#" alt="your image" name="img" style="width:150px;"/></td></tr> 
</table> 
<input type="hidden" name="module" value="visitor_add"> 
<center><input type="submit" value="Save and Proceed" /></center> 
</form> 

<script> 
function readURL(input) { 
if (input.files && input.files[0]) { 
    var reader = new FileReader(); 

    reader.onload = function (e) { 
     $('#img') 
      .attr('src', e.target.result) 
      .width(150) 
      .height(100); 
    }; 

    reader.readAsDataURL(input.files[0]); 
} 
} 
</script> 

這是我的jsp代碼來讀取輸入文件。我如何在服務方法中繼續使用我的java代碼?

回答

0

是的,它可以從jsp讀取數據並將其傳遞給java類/ Servlet,您可以從jsp頁面讀取文件uploades。

這是繼讀取多個文件和圖像,服務方法...

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
{ 
 // gets absolute path of the web application 
String appPath = request.getServletContext().getRealPath(""); 
// constructs path of the directory to save uploaded file 
String savePath = appPath + File.separator + SAVE_DIR; 

// creates the save directory if it does not exists 
File fileSaveDir = new File(savePath); 
if (!fileSaveDir.exists()) 
{ 
    fileSaveDir.mkdir(); 
} 

for (Part part : request.getParts()) 
{ 
      String fileName = extractFileName(part); 
     // refines the fileName in case it is an absolute path 
     fileName = new File(fileName).getName(); 
     part.write(savePath + File.separator + fileName); 
} 

request.setAttribute("message", "Upload has been done successfully!"); 
getServletContext().getRequestDispatcher("/message.jsp").forward(request, response); 

} 
/** 
* Extracts file name from HTTP header content-disposition 
*/ 
private String extractFileName(Part part) 
{ 
    String contentDisp = part.getHeader("content-disposition"); 
    String[] items = contentDisp.split(";"); 
    for (String s : items) { 
    if (s.trim().startsWith("filename")) { 
    return s.substring(s.indexOf("=") + 2, s.length()-1); 
} 
} 
    return ""; 
}