使用java类从jsp读取文件输入

时间:2017-06-12 06:22:48

标签: javascript java jsp

我希望我的jsp从本地机器读取图像文件并将其传递给我的java类。可能吗??或者它只能用java Servlet来完成?

<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代码?

1 个答案:

答案 0 :(得分:0)

是的,可以从jsp读取数据并将其传递给java class / 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 "";
 }