文件上传之后,并且对tomcat的设置问题记录

1、java代码

      参数:

                  HttpServletRequest request,UserPicture userPic, HttpServletResponse response,String userCode

           String imgUrl = uploadFileTo(request,response,userCode,userPic,"/Users/appletest/Desktop/uploadFile");   //最后的一个参数是路径

 

 

 

       将图片的路径传到数据库中:

           userPic.setUserPic(imgUrl);

userPictureService.updatePic(userPic);

 

 

 

封装一个文件上传的方法:

//图片处理

private String uploadFileTo(HttpServletRequest request, HttpServletResponse response, String userCode,UserPicture userPic,String basePath) {

CommonsMultipartFile file=userPic.getFile();

String imgUrl="";

if(file!=null){

 

//1.路径准备 mypath:根据自己的userCode

String mypath=userCode;   //自己定义的   

String targetImgPath=basePath+"/";

String imgName=mypath;

String pic_type = file.getContentType();

if(pic_type.equals("application/octet-stream")){//表示修改时,未点击图片,图片不做修改

return userPic.getUserPic();

}else if(pic_type.equals("image/jpeg")){

        imgName =   imgName.concat(".jpg");

        } else if (pic_type.equals("image/png")){

        imgName = imgName.concat(".png");

        } else if(pic_type.equals("image/bmp")){

        imgName =  imgName.concat(".bmp");

        } else if(pic_type.equals("image/gif")){

        imgName = imgName.concat(".gif");

        } else imgName = imgName.concat(".jpg");

//3.保存到数据库中的片路径

imgUrl=imgName;

//4.保存文件到指定的位置

 

try {

File targetFile=new File(targetImgPath,imgName);

if  (!targetFile.getParentFile().exists()){  

    targetFile.getParentFile().mkdirs();

}

if (!targetFile.exists()) {  

targetFile.createNewFile();  

        } 

file.transferTo(targetFile);

imgUrl = "/uploadFile/"+targetFile.getName(); 

}catch (Exception e) {

// TODO Auto-generated catch block

ResponseUtil.write(response, "<script language=\"javascript\">alert('上传图片发送异常!')</script>");

e.printStackTrace();

}

}

return imgUrl;

}

 

 

 

2、对tomct进行设置:

  <Context docBase="/Users/appletest/Desktop/uploadFile" path="/uploadFile" reloadable="true"/>

猜你喜欢

转载自www.cnblogs.com/haoxiu1004/p/9081693.html