文件上传

来源:互联网 发布:网络借贷法律 编辑:程序博客网 时间:2024/05/21 09:00

整理的文件上传demo如下:

 

1、jsp文件如下:

<table width="100%" border="0" cellspacing="1" cellpadding="5" class="form_table">                 <tr>                   <td width="12%" align="right" class="form_th">请上传 </td>                   <td width="28%" align="left" colspan="3">                   <s:file name="excelFile" id="excelFile" onkeypress="return false" onpaste="return false" onchange="ajaxFileUpload(this.value, 'excelFile')" label="上传" />                   </td>                   <td > </td>            </tr>               </table>


 

2、js文件如下:

/** * 上传 */function ajaxFileUpload(file,fileElementId){var ext = (/[.]/.exec(file))? /[^.]+$/.exec(file.toLowerCase()): "";if (!(ext && /^(xls)$/.test(ext))) {alert("不是2003格式的excel,请重新选择");return;}var url = "";var contextPath = $("#ctx").val();url = contextPath+'/viennamember/uploadExchangeOrderFile.action';$.ajaxFileUpload({     url:url,        //需要链接到服务器地址     secureuri:false,     fileElementId: fileElementId,                  //文件选择框的id属性                      timeout:50000,     dataType: 'json',           //服务器返回的格式,可以是json     success: function (data, status)                   {       if (fileElementId == 'excelFile') {     $("#filePath").val(data.filePath); }      },     error: function (data, status, e)                   {     alert("图片上传失败,请重新选择");     } });}


 

3、java文件如下:

访问控制层代码如下:

/** * 上传文件 *  * @return */public void uploadExchangeOrderFile() throws Exception {// 定义存放路径String savePath = Constants.EXCHANGE_ORDER_FILE_DIR;// 创建路径文件夹File dirFile = new File(savePath);if (!dirFile.exists()) {dirFile.mkdirs();}String timeStr = DateUtils.dateToString("yyyyMMddHHmmss");String fullPath = savePath +"exchangeorder_"+timeStr+".xls";iExchangeOrderService.uploadExchangeOrderFile(fullPath, excelFile);// 设置返回值HttpServletResponse response = ServletActionContext.getResponse();response.setContentType("text/html;charset=utf-8");response.getWriter().print("{filePath:'" + fullPath + "'}");response.flushBuffer();}


业务层代码如下:

public String uploadExchangeOrderFile(String fullPath, File excelFile) throws Exception {File file = new File(fullPath);// 指定文件存储的路径和文件名OutputStream os = new FileOutputStream(file);FileInputStream is = new FileInputStream(excelFile);byte[] b = new byte[1024];int len = 0;while ((len = is.read(b)) != -1) {os.write(b, 0, len);}os.close();is.close();return null;}


 

0 0
原创粉丝点击