javaweb项目中文件的本地下载与上传

 

首先在application.xml配置文件里添加配置

<bean id="multipartResolver" class="main.com.yjq.utils.CustomMultipartResolver">
           <!-- 设置上传文件的最大尺寸为10MB -->      
           <property name="defaultEncoding" value="UTF-8"></property>
           <property name="maxUploadSize">      
               <value>1048576000</value>      
           </property>      
               <property name="maxInMemorySize">    
               <value>1024</value>    
           </property>    
    </bean>

上一代码段中class的工具类

import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.ProgressListener;
import org.springframework.stereotype.Component;
@Component
public class FileUploadProgressListener implements ProgressListener {
    private HttpSession session;
    public void setSession(HttpSession session){
        this.session=session;
        Progress status = new Progress();//保存上传状态
        session.setAttribute("status", status);
    }
    @Override
    public void update(long bytesRead, long contentLength, int items) {
        Progress status = (Progress) session.getAttribute("status");
        status.setBytesRead(bytesRead);
        status.setContentLength(contentLength);
        status.setItems(items);

    }
}
package main.com.yjq.utils;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
public class CustomMultipartResolver extends CommonsMultipartResolver {
    // 注入第二步写的FileUploadProgressListener 
    @Autowired
    private FileUploadProgressListener progressListener;

    public void setFileUploadProgressListener(FileUploadProgressListener progressListener) {
        this.progressListener = progressListener;
    }

    @Override
    public MultipartParsingResult parseRequest(HttpServletRequest request) throws MultipartException {
        String encoding = determineEncoding(request);
        FileUpload fileUpload = prepareFileUpload(encoding);
        progressListener.setSession(request.getSession());
        fileUpload.setProgressListener(progressListener);
        try {
            List<FileItem> fileItems = ((ServletFileUpload) fileUpload).parseRequest(request);
            return parseFileItems(fileItems, encoding);
        } catch (FileUploadBase.SizeLimitExceededException ex) {
            throw new MaxUploadSizeExceededException(fileUpload.getSizeMax(), ex);
        } catch (FileUploadException ex) {
            throw new MultipartException("Could not parse multipart servlet request", ex);
        }
    }

}

以上准备工作完成后,写前端代码:

<form id="order" method="post" enctype="multipart/form-data" >  
 		<div style="margin:5px 0 10px 20px;">工作流程为首先上传需要操作的excel文件,格式支持.xls.xlsx,上传后点击‘开始处理...’,处理数据后选择导出文件。</div><br/>
        <input style='margin-left:20px;' id="uploadFile" type="file" name = "file" value="初始订单表">  
        <input type="button" value = "上传订单表" onclick = "submitOrder()"/>&nbsp;<span id="span_order"></span>&nbsp;<span>|</span>  
 </form> 

 文件上传并读取的代码

function submitOrder(){
		 var fileName = $("#uploadFile").val();  
         var index = fileName.lastIndexOf(".");  
         var suffix = fileName.substring(index).toLowerCase(); 
         if(fileName == "" || !(".xlsx" == suffix || ".xls" == suffix)) {  
        	 zeroModal.error("上传格式有误,请选择.xls/.xlsx格式上传");  
             return false;  
         }
         $("#zhezhao").slideDown();
 		$("#zhezhao_pic").slideDown();
		$('#order').ajaxSubmit({    
            url:'<%=request.getContextPath()%>/bjrb/checkimportIntoOrder',  
            dataType: 'json',
            type:'post',
            success: function(data){
            	getmsgfromorder();
            	if(data=="" || data==null){//返回空
            		$("#somem").hide();
            		$("#tishi").html("没有已处理过的信息");
					$("#ordertable").empty();
					$("#ordertable").hide();
				 }else{
					 $("#somem").show();
					 $("#ordertable").show();
					 $("#tishi").html("订单号数据重复,核对其他数据是否重复,如全部重复且已导入方正系统,请选择“处理不重复数据”,如部分重复请联系技术人员");
					$("#ordertable").empty();
					 $("#ordertable").append("<tr style='height: 24px;'><th>订单编号</th><th>收货人</th><th>收货人电话</th><th>地址</th><th>邮编</th><th>订单总额</th><th>创建时间</th><th>付款时间</th><th>支付类型</th><th>订报卡号</th><th>推荐人</th><th>发票类型</th><th>发票抬头</th><th>发票编号</th><th>订单状态</th><th>商品名称</th><th>礼品名称</th><th>购买数量</th><th>订购类型</th><th>礼品状态</th><th>配送单位</th><th>订购月数</th><th>配送开始时间</th><th>配送完成时间</th><th>操作时间</th></tr>");
				     for(var i=0;i<data.length;i++){
				     $("#ordertable").append("<tr id='c"+i+"'></tr>");
				     if(i%6==2){
				    	 document.getElementById('c'+i).style.background = 'rgb(247, 247, 247)';
		    		 }
			    	 if(i%6==5){
				    	 document.getElementById('c'+i).style.background = 'rgb(255, 250, 250)';
		    		 }
				     $("#"+"c"+i).append("<td style='width:10px'>"+data[i].order_num+"</td>");
				     $("#"+"c"+i).append("<td>"+data[i].order_name+"</td>");
				     $("#"+"c"+i).append("<td>"+data[i].order_phone+"</td>");
				     $("#"+"c"+i).append("<td>"+data[i].order_address+"</td>");
				     }
				     $("#order_top").show();
				}
				   
					 $("#zhezhao").slideUp();
					$("#zhezhao_pic").slideUp();
            },  
            error: function(){
            	
            }  
        });
		
		
	}
@RequestMapping(value = "checkimportIntoOrder")  
	public void checkimportIntoOrder(MultipartFile file,HttpServletResponse response,HttpServletRequest req) throws IOException, InvalidFormatException {
		List<PaperOrder> list = new ArrayList<PaperOrder>();
		List<OrderHistory> list1 = new ArrayList<OrderHistory>();
		String filename = file.getOriginalFilename();
		req.getSession().setAttribute("orderfilename", filename);
		InputStream in = file.getInputStream();
		//获取文件输入流  
		Workbook create = WorkbookFactory.create(in);
		Sheet sheet = create.getSheetAt(0);  //获取Excel的第一个子页  
		Row row = null;
		orderService.deleteFromOrder();
		int maxRowIx = sheet.getLastRowNum();
		for(int i=1;i<(maxRowIx+1);i++){    
			row = sheet.getRow(i);  //第几个格子  
			short minColIx = row.getFirstCellNum();  
			short lastCellNum = row.getLastCellNum();
			String cellvalues = "";
			for(int j = minColIx;j<lastCellNum;j++){
				Cell cell = row.getCell(j);
				String cellValue;
				if(cell == null){
					cellValue = "";
				}else{
					cell.setCellType(Cell.CELL_TYPE_STRING);
					cellValue = row.getCell(j).getStringCellValue();
				}
				cellvalues+=cellValue+",";
			}
			String[] value = cellvalues.split(",");
			PaperOrder order = new PaperOrder();
			order.setOrder_num(value[0]);
			order.setOrder_name(value[1]);
			order.setOrder_phone(value[2]);
			order.setOrder_address(value[3]);
			order.setOrder_postcode(value[4]);
			order.setOrder_price(value[5]);
			order.setOrder_createdate(value[6]);
			order.setOrder_paydate(value[7]);
			order.setOrder_paytype(value[8]);
			order.setOrder_newspaper_num(value[9]);
			order.setTuijianren(value[10]);
			order.setInvoice_type(value[11]);
			order.setInvoice_title(value[12]);
			order.setInvoice_num(value[13]);
			order.setOrder_status(value[14]);
			order.setCommodity_name(value[15]);
			order.setGift_name(value[16]);
			order.setBuy_number(value[17]);
			order.setBuy_type(value[18]);
			order.setGift_status(value[19]);
			order.setSend_danwei(value[20]);
			order.setSend_num(value[21]);
			order.setSend_liushui(value[22]);
			order.setOrder_contain_month(value[23]);
			order.setSend_startdate(value[24]);
			order.setSend_enddate(value[25]);
			OrderHistory num = orderService.selectFromHorder(value[0]);
			if(num!=null) {
				list1.add(num);
			}
			list.add(order);
		}
		orderService.insertintoTwotable(list);
		//JsonUtil.outputJsonArry(response, JSONArray.fromObject(list));
		//重复数据
		JsonUtil.outputJsonArry(response, JSONArray.fromObject(list1));
	}

文件下载到本地的代码,主要是设置response的头信息。

@RequestMapping(value = "importOptionedOrder")  
	public void importOptionedOrder(HttpServletResponse response,HttpServletRequest req) throws IOException, RowsExceededException, WriteException{
		//Cookie[] cookies = req.getCookies();
		/*for (Cookie cookie : cookies) {
			System.out.println(cookie.getValue());
		}*/
		String filename = (String) req.getSession().getAttribute("orderfilename");
		OutputStream os = response.getOutputStream();// 取得输出流
		response.reset();// 清空输出流logrb/downloadExcel
		String strname = new String(filename.getBytes("gb2312"),"iso-8859-1");
		response.setHeader("Content-disposition", "attachment; filename="+strname);// 设定输出文件头
		response.setContentType("application/msexcel");// 定义输出类型
		List<OrderHistory> orderHistroy = orderService.selectFromOrderHistroy();
		for (int k=0;k<orderHistroy.size();k++) {
			if(orderHistroy.get(k).getOrder_newspaper_num().equals("无")) {
				orderHistroy.remove(k);
			}
		}
	    String[] title = {"订单编号","收货人","收货人电话","地址","邮编","订单总额","创建时间","付款时间","支付类型","订报卡号","推荐人","发票类型","发票抬头","发票编号","订单状态","商品名称","礼品名称","购买数量","订购类型","礼品状态","配送单位","配送编号","配送流水","订购月数","配送开始时间","配送完成时间","价格"};
    	//OutputStream os = new FileOutputStream(filePath);     
        WritableWorkbook wwb=Workbook.createWorkbook(os);      
        WritableSheet sheet = wwb.createSheet("订单表", 0);     
        Label label;     
        for(int i=0;i<title.length;i++){     
           label = new Label(i,0,title[i]);     
          sheet.addCell(label);     
        }     
        for(int i=0;i<orderHistroy.size();i++){  
        		label = new Label(0,i+1,orderHistroy.get(i).getOrder_num());
        		sheet.addCell(label);
        		label = new Label(1,i+1,orderHistroy.get(i).getOrder_name());
        		sheet.addCell(label);
        		label = new Label(2,i+1,orderHistroy.get(i).getOrder_phone());
        		sheet.addCell(label);
        		label = new Label(3,i+1,orderHistroy.get(i).getOrder_address());
        		sheet.addCell(label);
        		label = new Label(4,i+1,orderHistroy.get(i).getOrder_postcode());
        		sheet.addCell(label);
        		label = new Label(5,i+1,orderHistroy.get(i).getOrder_price());
        		sheet.addCell(label);
        		label = new Label(6,i+1,orderHistroy.get(i).getOrder_createdate());
        		sheet.addCell(label);
        		label = new Label(7,i+1,orderHistroy.get(i).getOrder_paydate());
        		sheet.addCell(label);
        		label = new Label(8,i+1,orderHistroy.get(i).getOrder_paytype());
        		sheet.addCell(label);
        		label = new Label(9,i+1,orderHistroy.get(i).getOrder_newspaper_num());
        		sheet.addCell(label);
        		label = new Label(10,i+1,orderHistroy.get(i).getTuijianren());
        		sheet.addCell(label);
        		label = new Label(11,i+1,orderHistroy.get(i).getInvoice_type());
        		sheet.addCell(label);
        		label = new Label(12,i+1,orderHistroy.get(i).getInvoice_title());
        		sheet.addCell(label);
        		label = new Label(13,i+1,orderHistroy.get(i).getInvoice_num());
        		sheet.addCell(label);
        		label = new Label(14,i+1,orderHistroy.get(i).getOrder_status());
        		sheet.addCell(label);
        		label = new Label(15,i+1,orderHistroy.get(i).getCommodity_name());
        		sheet.addCell(label);
        		label = new Label(16,i+1,orderHistroy.get(i).getGift_name());
        		sheet.addCell(label);
        		label = new Label(17,i+1,orderHistroy.get(i).getBuy_number());
        		sheet.addCell(label);
        		label = new Label(18,i+1,orderHistroy.get(i).getBuy_type());
        		sheet.addCell(label);
        		label = new Label(19,i+1,orderHistroy.get(i).getGift_status());
        		sheet.addCell(label);
        		label = new Label(20,i+1,orderHistroy.get(i).getSend_danwei());
        		sheet.addCell(label);
        		label = new Label(21,i+1,orderHistroy.get(i).getSend_num());
        		sheet.addCell(label);
        		label = new Label(22,i+1,orderHistroy.get(i).getSend_liushui());
        		sheet.addCell(label);
        		label = new Label(23,i+1,orderHistroy.get(i).getOrder_contain_month());
        		sheet.addCell(label);
        		label = new Label(24,i+1,orderHistroy.get(i).getSend_startdate());
        		sheet.addCell(label);
        		label = new Label(25,i+1,orderHistroy.get(i).getSend_enddate());
        		sheet.addCell(label);
        		label = new Label(26,i+1,orderHistroy.get(i).getPrice());
        		sheet.addCell(label);
         }    
        wwb.write();     
        wwb.close(); 
        os.close(); 
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值