<div id="image-holder" style="margin:0 auto;width:200px;height:250px;border:1px solid gray">
<img src="" style="width:100%;height:100%">
</div>
<input style="margin:0 auto;" type="file" id="id_pic_upload" name="name_pic">
<button type="button" class="btn btn-primary" id="id_ok_upload">上传</button>
//上传图片预览
$("#id_pic_upload").on('change', function () {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function(e){
$("#image-holder img").attr("src",e.target.result);
}
reader.readAsDataURL($(this)[0].files[0]);
} else {
Tools_ShowMsg("设备不支持预览,可尝试升级");
}
//ajax上传
//id_ok_upload 任意按钮
$("#id_ok_upload").click(function(){
var formData = new FormData();
formData.append('name_pic', $('#id_pic_upload')[0].files[0]); //name_pic 为后台接收名称,id_pic_upload为file类型input
$.ajax({
url:"servlet/FileServlet",
type:"post",
cache:false,
data:formData,
processData:false,
contentType:false,
success:function(data)
{
console.log("success");
},
error:function(err)
{
console.log("error");
}
});
});
//jsp
<form action="uploadservlet" method="post" enctype="multipart/form-data">
<input type="file" name="pic">
<input type="submit" name="submit">
</form>
//servlet
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
if(ServletFileUpload.isMultipartContent(request))
{
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> items = upload.parseRequest(request);
Iterator<FileItem> it = items.iterator();
while(it.hasNext())
{
FileItem item = it.next();
if(item.isFormField())
{
}else
{
if(item.getFieldName().equals("pic"))
{
String fileName = item.getName();
String path = request.getSession().getServletContext().getRealPath("upload");
File file = new File(path,fileName);
item.write(file);
System.out.println(fileName + " 上传成功");
}
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
网友评论