关于ajaxfileupload.js上传图片使用历程(struts2)

  因为要使用上传图片功能,附加图片的描述信息, 而传统的<s: file/>由于一些限制在这个小模块中无法使用, 于是搜到了使用ajaxfileupload.js插件进行上传的方法,在使用过程中,jsp,js,struts2

  因为自己不熟悉ajax的情况出了许多的小问题,在这里记录一下, 方便自己查看,也希望能帮到他人,

  首先说一下思路,通过点击上传直接触发js 的function 调用后台把图片拷贝到指定服务器目录,返回保存的路径到前台,然后跟随图片描述信息一起用ajax异步传到后台。(PS:如果有新的方法,麻烦请告知,我只会这个了)

  首先,我先把jsp代码贴上来,

<input type="file" onchange="uploadImage(this)" id="newsImgFile" name="tbslidefile" />
<input type="hidden" id="imgPath"  name="imgPath" />

<div class="newlyhead">标题:</div>
<div class="newlycontent"><input type="text" class="upload_title" id="slideTitle" name="slideTitle"></div>
<input type="button"  value="保    存"  onclick="saveTwo();"  >

记得添加进来需要的js插件,这里我自己写的js叫做index.js

<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/ajaxfileupload.js"></script>
<script type="text/javascript" src="js/index.js"></script>

下面是我自己写的js代码

function uploadImage(obj) {
    var fileElementId = "newsImgFile";  //注意这里newsImgFile是上面 input type="file"的 id 如果需要修改记得一起修改
    $("#newsImgFile").attr('name','file');  //明显.attr就是设置元素的属性值,当然如果单纯上传图片的话可以不用这么麻烦,直接在下面fileElementId:**属性跟input的id name一致就OK了,通过再次转换,可以方便在js中进行不同图片的控制,当然这里没用到
    alert("test");  //只是查看是否执行到了这里,可以去掉          
        $.ajaxFileUpload({
            url:'uploadAction',       //需要链接到服务器地址
            secureuri:false,
            fileElementId:fileElementId,                            //文件选择框的id属性
            dataType: 'json',                                   //服务器返回的格式,可以是其他
            success: function (response, status, xhr) {               //成功后的回调函数
                console.log(response.obj);            //这个方法可以在浏览器(chrome等)审查元素时候控制台console输出
                    //alert(response.obj);
                    $('#imgPath').val(response.obj);      //这个就是为上面input id="imgPath"赋值,一起传到后台
            },
            error: function (data, status, e) {           //相当于java中catch语句块的用法
                $('#imgPath').val('');
            }
        });
}

function saveTwo()
{
    $.ajax({ 
    type: "post",
    dataType: "text",
    contentType:"application/x-www-form-urlencoded; charset=utf-8",
    url: "addSlide",     //都是Action因为是使用struts2框架
    data: {
        slideTitle:$("#slideTitle").val(),
        slidePath:$("#imgPath").val()
    },
    success: function(response, status, xhr) {
        console.log(response);  //response是返回的值
        alert(status);    //status是状态,例如success
        if(status=="success")
        {
            jAlert("添加成功!","提示信息");
        } 
        else
        {
            jAlert("添加失败!","提示信息");
        }
    } });
}

相信上面关于js的说明会很清楚,接下来是后台代码,单纯接收到js上传的图片并返回路径到前面js

package *****
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

/**
 *@author  E—mail:
 *@version  create time:2014-6-16上午10:43:43
 *class introduce
 */
public class UploadAction extends ActionSupport {

    private File file;
    private String fileFileName;
    
    private String savePath;
    private String obj;
    /**
     * 私有变量file要和js中$("#newsImgFile").attr('name','file');一致,这样可以直接接受过来
     * 这里是单纯的图片上传到服务器,这个savePath是在struts.xml中配置的
     * 
     *  
     */
    @Override
    public String execute() throws Exception {
        String bigurl = "";
        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
        Date now = new Date();
        String dDir = sf.format(now);
        String fExt = fileFileName.substring(fileFileName.lastIndexOf("."));
        String savePath = ServletActionContext.getServletContext().getRealPath(this.getSavePath());
        bigurl = savePath+"\\"+dDir + fExt;
        try {
            File f = this.getFile();
            FileInputStream inputStream = new FileInputStream(f);
            FileOutputStream outputStream = new FileOutputStream(bigurl);
            byte[] buf = new byte[1024];
            int length = 0;
            while ((length = inputStream.read(buf)) != -1) {
                outputStream.write(buf, 0, length);
            }
            inputStream.close();
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        //直接是字符串前面就可以接收到,要是跟下面注释一样转换成json前面还要转换,我试过这样可以直接在前面js中response得到,
        obj =bigurl.substring(bigurl.lastIndexOf("fileResources")) ;    
//        System.out.println("\"success\":true,\"url\":\""+dDir+"/"+fExt+"\",\"bigurl\":\""+bigurl+"\"");
//        JSONObject jsonobj = JSONObject.fromObject(path);
//        obj = jsonobj.toString();

        return SUCCESS;
    }

    public File getFile() {
        return file;
    }

    public void setFile(File file) {
        this.file = file;
    }

    public String getFileFileName() {
        return fileFileName;
    }

    public void setFileFileName(String fileFileName) {
        this.fileFileName = fileFileName;
    }

    public String getSavePath() {
        return savePath;
    }

    public void setSavePath(String savePath) {
        this.savePath = savePath;
    }

    public String getObj() {
        return obj;
    }

    public void setObj(String obj) {
        this.obj = obj;
    }
}

至于传图片路径和图片标题到后台,得到并保存,就是淡出的struts2后台处理,就没必要贴出来了,

struts.xml中配置这个Action

<action name="uploadAction" class="com.gt.***.action.UploadAction" >
    <param name="savePath">/fileResources/imageFile</param>
    <result name="success" type="json">
        <param name="contentType">
            text/html
        </param>            
    </result>
</action>

至于为什么param是这样的,我没仔细深究,如果有朋友知道麻烦告诉我,谢谢。

另外ajaxfileupload.js插件很好获得,百度一下你就可以哈哈。

 

 

转载于:https://www.cnblogs.com/2589-spark/p/3796205.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值