上传图片

********

1,jsp页面

2,后台struts的action中

public boolean saveAttach(TBasePhotoAttach photo) throws Exception{
        /*System.out.println(upload1FileName); //flower.jpg
        System.out.println(upload1); 
        System.out.println(upload1ContentType); //image/pjpeg   */

    //只能上传这些格式的图片
if(!"image/jpeg".equals(upload1ContentType) &&!"image/gif".equals(upload1ContentType) &&!"image/pjpeg".equals(upload1ContentType)){ return false; }
    //图片名 String photoName
= upload1FileName.substring(0,upload1FileName.lastIndexOf("."));
    //图片后缀 String suffix
=upload1FileName.substring(upload1FileName.lastIndexOf(".")+1);
    //加上毫秒,有时因为批量上传图片,导致名字相同而被覆盖,所以加上毫秒较好 SimpleDateFormat format
=new SimpleDateFormat("yyyyMMddhhmmssSSS"); //使用当前时间为图片命名 String newName=format.format(new Date())+"."+suffix; //用于保存上传照片的文件夹 String uploadPath=this.getRequest().getRealPath("/")+"uploadImages"; // E:JavaWorkspace dp WebRoot uploadImages File file=new File(uploadPath); if(!file.exists()){ file.mkdirs(); } String saveUrl=uploadPath +"\"+ newName; //完整保存路径 //文件输入流 FileInputStream fis = new FileInputStream(upload1); //文件输出流 FileOutputStream fos = new FileOutputStream(saveUrl, false); byte buffer[] = new byte[4096]; int readSize = 0; //存储文件 while ((readSize = fis.read(buffer)) > 0) { fos.write(buffer, 0, readSize); } //photo.setPhotoUrl(saveUrl); //URLEncoder.encode(upload1FileName, "UTF-8"); //DATE.getCurrentDate().toString() String photoUrl=this.getRequest().getContextPath()+"/uploadImages/"+newName; photo.setPhotoUrl(photoUrl); photo.setOldname(upload1FileName); photo.setNewname(newName); stuService.savePhoto(photo); return true; }

 二,批量上传

1,后台

public void saveGroupPhotos() throws Exception{
        //构建保存路径
        String uploadPath=this.getRequest().getRealPath("/")+"uploadImages";
        File file=new File(uploadPath);
        if(!file.exists()){
            file.mkdirs();
        }
        SimpleDateFormat format=new SimpleDateFormat("yyyyMMddhhmmssSSS");
        
        FileInputStream fis=null;
        FileOutputStream fos=null;
        String suffix=null;
        String saveUrl=null;
        
        for(int i=0;i<group.size();i++){
            fis=new FileInputStream(group.get(i));
            
            suffix=groupFileName.get(i).substring(groupFileName.get(i).lastIndexOf("."));
            saveUrl=uploadPath+File.separator+format.format(new Date())+suffix;
            fos=new FileOutputStream(saveUrl,false);
            
            int len=0;
            byte[] bytes=new byte[1024];
            //开始read里没写实参,文件图片一直为损坏状态
            while((len=fis.read(bytes))>0){
                fos.write(bytes,0,len);
            }
        }
        
        
        
        
    }

2,前台

function addMore(){
               $("#upload").append("<input type='file' name='group'>");
               
       }


<form action="<%=path%>/test/test!saveGroupPhotos.action" method="post" enctype="multipart/form-data">
<div id="upload">
<input type="file" name="group" label="文件1">


</div>
<input type="button" value="add more.." onclick="addMore();">
<input type="submit" value="提交">
</form>

 

 三,使用jquery插件批量上传图片

<script src="<%=jsRoot %>/jquery/jquery.MultiFile.js" type="text/javascript" language="javascript"></script>


//即刻显示上传的图片
function view(){
var filepath=$("#upload1").val();
var suffix=filepath.substr(filepath.indexOf(".")+1);
if("jpg"==suffix||"png"==suffix||"bmp"==suffix||"jpeg"==suffix){
$("#preview img").attr("src",filepath);
$("#preview").show();
}else{
alert("图片格式不正确");
return;
}

}
//页面加载完成后,
$(function(){
//alert($("#show img").attr("src"));
var photourl=$("#photourl").val();
if(photourl==""||photourl==null){
$("#preview").hide();
}
});


/******/
function del(id){
$("#"+id).remove();
var input="<input name='deletePhotoIds' type='hidden' value='"+id+"'/>"
$("#deleteAttachDiv").append(input);
}

<fieldset>
<legend>民主评议照片上传</legend>
<%-- <input type="file" class="input_text" name="upload1" id="upload1" style=" 60%" onchange="view();"/>
<br><br>
<div id="preview">
<img width="100px" height="100px" alt="" src="${photoModel.photoUrl }"/>
</div>

--%>

<form action="<%=path%>/student/student!savePreparePhoto.action"
method="post" onsubmit="return checkform();" enctype="multipart/form-data" target="actionframe2">

<input type="hidden" name="photoModel.photoUrl" id="photourl" value="${photoModel.photoUrl}">
<div id="deleteAttachDiv" style="display: none;">
</div>


<input type="file" class="multi" name="upload" id="upload" style=" 100%;">
<s:if test="photosModel != null">

<s:iterator value="photosModel" var="attch">
<div class="MultiFile-label" id="${id }" flag="1">
<li>
<a class="MultiFile-remove" href="#" onclick="del('${id }')">删除</a>
<%-- <img width="100px" height="100px" alt="" src="${photoUrl }"/> --%>
<span class="MultiFile-title">${oldname }</span>
</li>

</div>
</s:iterator>
</s:if>

</fieldset>

*************

有问题在公众号【清汤袭人】找我,时常冒出各种傻问题,然一通百通,其乐无穷,一起探讨


原文地址:https://www.cnblogs.com/qingmaple/p/4090324.html