草庐IT

java-文件上传-excel存入数据库全代码及流程(附前端代码)

喜欢写bug嘻嘻嘻 2024-01-21 原文

今天给大家带来的是文件上传中比较常用的,上传excel文件,将表格中的数据存入数据库中的一个转化的工具类;大致的流程是:前端点击上传按钮-->选择需要上传的excel表格-->确认上传-->    文件传到后台-->后台处理file文件-->将文件转化成List-->将List集合存入数据库

首先通过前端点击按钮:

  <button type="button" id="input" data-loading-text="正在上传..." class="btn btn-default">        
     导入
  <i class="fa fa-upload"></i></button>

点击导入按钮,触发input框点击事件:

             $('#input').click(function () {
                $('#import_modal').modal('show');
            })

 点击按钮后,弹出框:

 弹窗代码:

          <div class="modal fade" id="import_modal">
                <div class="modal-dialog" style="max-height:80%">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal">
                                <span aria-hidden="true">&times;</span>
                                <span class="sr-only">Close</span>
                            </button>
                            <h4 class="modal-title">上传数据</h4>
                        </div>
                        <div class="modal-body" style="overflow: auto;
                                 max-hieght:800px;">
                            <div class="container-fluid"  style="height: 300px;">
                                <form class="form-horizontal" 
                                        enctype="multipart/form-data">
                                    <div class="form-group">
                                        <label for="file" class="col-sm-3 control-label">                    
                                           上传文件</label>
                                        <div class="col-sm-4">
                                            <input class="form-control" accept=".xlsx" 
                                                   style="padding:3px;" type="file"
                                                   id="file" name="file"/>
                                        </div>
                                    </div>
                                </form>
                            </div>

                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-primary" id="import" 
                                     data-loading-text="正在上传...">确定
                            </button>
                            <button type="button" class="btn btn-default" data- 
                                        dismiss="modal">取消</button>
                        </div>
                    </div>
                </div>
            </div>

选择要上传的文件,然后点击确定:

点击确定触发:将请求地址改成自己本地的

 $('#import_modal form').bootstrapValidator('destroy');
            $('#import_modal form').bootstrapValidator({
                message: '输入不合法',
                fields: {
                    file: {
                        validators: {
                            notEmpty: {message: '文件不能为空'}
                        }
                    }
                }
            }).on('success.form.bv', function (e) {

                var files = $("#file").get(0).files;
                if (files.length > 0) {
                    if (files[0].size > 1024 * 1024 * 100) {
                        alert('文件大小不能超过100MB');
                        return false;
                    }
                    var formData = new FormData();
                    formData.append('file', files[0]);
                    $.ajax({
                        url: 
              '${pageContext.request.contextPath}/backend/form/evaluation_update/import',
                        type: 'POST',
                        cache: false,
                        data: formData,
                        processData: false,
                        contentType: false,
                        dataType: "json",
                        beforeSend: function () {
                            $('#import').button('loading');
                        },
                        success: function (data) {
                            if (data.errorCode === 0) {
                                alert(data.message);
                                $('#import_modal').modal('hide');
                                location.reload();
                            } else {
                                alert(data.message);
                            }
                            $('#import').button('reset');
                        }, error: function () {
                            $('#import').button('reset');
                        }
                    });
                }
            });

请求到后台:

poi依赖

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.14</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.14</version>
        </dependency>

controller层

@RequestMapping("evaluation_update/import")
    @ResponseBody
    public Result evaluationUpdate(@RequestParam(value = "file", required = true) MultipartFile file,
                                  UserSession session) throws Exception {
        try {
            Result result = new Result();
            result.setMessage("导入成功");
            int count = wfOrderService.importAnnualDemand(session, file);
            result.setMessage(count > 0 ? "导入成功,共:" + count + "条记录!" : "本次导入0条数据!");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

service层:

public int importAnnualDemand(UserSession session, MultipartFile file) throws ErrorCodeException {

		List<Map<String, ArrayList<String[]>>> allDateList = new ArrayList<>();
		List<Requirement>list=new ArrayList<>();
		List<String[]> dataList;
		try {
			String filePath=getFilePath(file);
			Map<String,Object> insert = new HashMap();
			insert.put("file", filePath);
			File excelFile = uploadManager.file(filePath);
			dataList = POIExcelUtil.readExcel(excelFile, 1, false);
			System.out.println(dataList);
			for (String[] strings : dataList) {
				Requirement r = new Requirement();
				r.setErpCode(strings[0]);
				r.setAnnualDemand(new BigDecimal(strings[1]));
				r.setYear(strings[2]);
				list.add(r);
			}
			if(!list.isEmpty()){
				return this.insert(STATEMENT_ID + "importAnnualDemand", list);
			}
			return 0;

		}catch (Exception e){
			e.printStackTrace();
			return 0;
		}
	}
POIExcelUtil.readExcel工具类代码(拷贝即用):
//包名

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;

public class POIExcelUtil {
    private final static String XLS = "xls";
    private final static String XLSX = "xlsx";


    private static NumberFormat numberFormat = NumberFormat.getNumberInstance();

    static {
        numberFormat.setGroupingUsed(false);
    }


    public static List<String[]> readExcel(File file, int firstRowNum, boolean needTitle) throws IOException {
        // 检查文件
        checkFile(file);
        Workbook workBook = getWorkBook(file);
        // 返回对象,每行作为一个数组,放在集合返回
        ArrayList<String[]> rowList = new ArrayList<>();
        if (null != workBook) {
            // 获得当前sheet工作表
            Sheet sheet = workBook.getSheetAt(0);
            if (sheet != null) {
                // 获得当前sheet的结束行
                int lastRowNum = sheet.getLastRowNum();
                sheet.getSheetName();
                int firstCellNum = sheet.getRow(firstRowNum - 1).getFirstCellNum();
                int lastCellNum = sheet.getRow(firstRowNum - 1).getLastCellNum();
                if (lastCellNum > 200) {
                    lastCellNum = 200;
                }

                if (needTitle) {
                    // 获取标题行,并返回在第一个list元素
                    Row titleRow = sheet.getRow(firstRowNum - 1);
                    String[] titleCells = new String[lastCellNum];
                    // 循环当前行
                    for (int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++) {
                        Cell cell = titleRow.getCell(cellNum);
                        titleCells[cellNum] = getOriginalCellValue(cell);
                    }
                    rowList.add(titleCells);
                }

                // 循环所有行数据
                for (int rowNum = firstRowNum; rowNum <= lastRowNum; rowNum++) {
                    // 获得当前行
                    Row row = sheet.getRow(rowNum);
                    if (row == null) {
                        continue;
                    }
                    String[] cells = new String[lastCellNum];
                    // 循环当前行
                    for (int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++) {
                        Cell cell = row.getCell(cellNum);
                        cells[cellNum] = getOriginalCellValue(cell);
                    }
                    rowList.add(cells);
                }
            }
            workBook.close();
        }

        return rowList;
    }


    public static List<String[]> readExcelPrecision(File file, int firstRowNum) throws IOException {
        // 检查文件
        checkFile(file);
        Workbook workBook = getWorkBook(file);
        // 返回对象,每行作为一个数组,放在集合返回
        ArrayList<String[]> rowList = new ArrayList<>();
        if (null != workBook) {
            // 获得当前sheet工作表
            Sheet sheet = workBook.getSheetAt(0);
            if (sheet != null) {
                // 获得当前sheet的结束行
                int lastRowNum = sheet.getLastRowNum();
                sheet.getSheetName();
                int firstCellNum = sheet.getRow(firstRowNum - 1).getFirstCellNum();
                int lastCellNum = sheet.getRow(firstRowNum - 1).getLastCellNum();
                if (lastCellNum > 200) {
                    lastCellNum = 200;
                }

                // 循环所有行数据
                for (int rowNum = firstRowNum; rowNum <= lastRowNum; rowNum++) {
                    // 获得当前行
                    Row row = sheet.getRow(rowNum);
                    if (row == null) {
                        continue;
                    }
                    String[] cells = new String[lastCellNum];
                    // 循环当前行
                    for (int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++) {
                        Cell cell = row.getCell(cellNum);
                        cells[cellNum] = getOriginalCellValuePrecision(cell);
                    }
                    rowList.add(cells);
                }
            }
            workBook.close();
        }

        return rowList;
    }


    public static List<Map<String, ArrayList<String[]>>> readMultiExcel(File file, int firstRowNum, int firstRowNum2, boolean needTitle) throws IOException {
        // 检查文件
        checkFile(file);
        Workbook workBook = getWorkBook(file);
        List<Map<String, ArrayList<String[]>>> resultList = new ArrayList<>();
        // 返回对象,每行作为一个数组,放在集合返回

        if (null != workBook) {
            // 获得当前sheet工作表
            for (int w = 0; w < workBook.getNumberOfSheets(); w++) {
                Sheet sheet = workBook.getSheetAt(w);
                if (sheet != null) {
                    ArrayList<String[]> rowList = new ArrayList<>();
                    Map<String, ArrayList<String[]>> sheetMap = new HashMap<>();
                    String sheetName = sheet.getSheetName();
                    // 获得当前sheet的结束行
                    int lastRowNum = sheet.getLastRowNum();
                    int firstCellNum = sheet.getRow(w > 0 ? firstRowNum2 - 1 : firstRowNum - 1).getFirstCellNum();
                    int lastCellNum = sheet.getRow(w > 0 ? firstRowNum2 - 1 : firstRowNum - 1).getLastCellNum();
                    if (needTitle) {
                        // 获取标题行,并返回在第一个list元素
                        Row titleRow = sheet.getRow(w > 0 ? firstRowNum2 - 1 : firstRowNum - 1);
                        String[] titleCells = new String[lastCellNum];
                        // 循环当前行
                        for (int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++) {
                            Cell cell = titleRow.getCell(cellNum);
                            titleCells[cellNum] = getOriginalCellValueByMulti(cell);
                        }
                        rowList.add(titleCells);
                    }
                    // 循环所有行数据
                    for (int rowNum = w > 0 ? firstRowNum2 - 1 : firstRowNum - 1; rowNum <= lastRowNum; rowNum++) {
                        // 获得当前行
                        Row row = sheet.getRow(rowNum);
                        if (row == null) {
                            continue;
                        }
                        String[] cells = new String[lastCellNum];
                        // 循环当前行
                        for (int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++) {
                            Cell cell = row.getCell(cellNum);
                            cells[cellNum] = getOriginalCellValueByMulti(cell);
                        }
                        rowList.add(cells);
                    }
                    sheetMap.put(sheetName, rowList);
                    resultList.add(sheetMap);
                }
            }
            workBook.close();
        }
        return resultList;
    }


    public static String getOriginalCellValueByMulti(Cell cell) {
        DecimalFormat originalValueDecimalFormat = new DecimalFormat("#.##");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        if (cell == null) {
            return "";
        }
        int cellType = cell.getCellType();
        switch (cellType) {
            case Cell.CELL_TYPE_FORMULA:
                return numberFormat.format(cell.getNumericCellValue());
            case Cell.CELL_TYPE_NUMERIC:
                if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {
                    Date dateCellValue = cell.getDateCellValue();
                    if (dateCellValue != null) {
                        return simpleDateFormat.format(dateCellValue);
                    }
                    return "";
                }
                return originalValueDecimalFormat
                        .format(cell.getNumericCellValue());
            case Cell.CELL_TYPE_STRING:
                return cell.getStringCellValue();
            case Cell.CELL_TYPE_BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case Cell.CELL_TYPE_BLANK:
                return "";
            case Cell.CELL_TYPE_ERROR:
                return String.valueOf(cell.getErrorCellValue());
        }
        return "";
    }


    public static String getOriginalCellValue(Cell cell) {
        DecimalFormat originalValueDecimalFormat = new DecimalFormat("#.##");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        if (cell == null) {
            return "";
        }
        int cellType = cell.getCellType();
        switch (cellType) {
            case Cell.CELL_TYPE_FORMULA:
                return String.valueOf(cell.getNumericCellValue());
            case Cell.CELL_TYPE_NUMERIC:
                if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {
                    Date dateCellValue = cell.getDateCellValue();
                    if (dateCellValue != null) {
                        return simpleDateFormat.format(dateCellValue);
                    }
                    return "";
                }
                return originalValueDecimalFormat
                        .format(cell.getNumericCellValue());
            case Cell.CELL_TYPE_STRING:
                return cell.getStringCellValue();
            case Cell.CELL_TYPE_BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case Cell.CELL_TYPE_BLANK:
                return "";
            case Cell.CELL_TYPE_ERROR:
                return String.valueOf(cell.getErrorCellValue());
        }
        return "";
    }

    public static String getOriginalCellValuePrecision(Cell cell) {
        DecimalFormat originalValueDecimalFormat = new DecimalFormat("#.####");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        if (cell == null) {
            return "";
        }
        int cellType = cell.getCellType();
        switch (cellType) {
            case Cell.CELL_TYPE_FORMULA:
                return String.valueOf(cell.getNumericCellValue());
            case Cell.CELL_TYPE_NUMERIC:
                if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {
                    Date dateCellValue = cell.getDateCellValue();
                    if (dateCellValue != null) {
                        return simpleDateFormat.format(dateCellValue);
                    }
                    return "";
                }
                return originalValueDecimalFormat
                        .format(cell.getNumericCellValue());
            case Cell.CELL_TYPE_STRING:
                return cell.getStringCellValue();
            case Cell.CELL_TYPE_BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case Cell.CELL_TYPE_BLANK:
                return "";
            case Cell.CELL_TYPE_ERROR:
                return String.valueOf(cell.getErrorCellValue());
        }
        return "";
    }


    /**
     * 获得工作簿对象
     */
    private static Workbook getWorkBook(File file) throws IOException {
        String filename = file.getName();
        Workbook workbook = null;
        InputStream is = new FileInputStream(file);
        if (filename.endsWith(XLS)) {
            // 2003
            workbook = new HSSFWorkbook(is);
        } else if (filename.endsWith(XLSX)) {
            // 2007
            workbook = new XSSFWorkbook(is);
        }
        return workbook;
    }

    /**
     * 检查文件
     */
    private static void checkFile(File file) throws IOException {
        if (null == file) {
            throw new FileNotFoundException("文件不存在!");
        }
        // 获取文件名
        String filename = file.getName();
        // 判断是否为excel文件
        if (!filename.endsWith(XLS) && !filename.endsWith(XLSX)) {
            throw new IOException(filename + "不是excel文件");
        }
    }

    /**
     * 取单元格的值
     */
    private static String getCellValue(Cell cell) {
        String cellValue = "";
        if (cell == null) {
            return cellValue;
        }
        // 把数字当成String来读,防止1读成1.0
        if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            // 日期格式
            short format = cell.getCellStyle().getDataFormat();
            if (format == 14 || format == 31 || format == 57 || format == 58
                    || (182 <= format && format <= 196)
                    || (210 <= format && format <= 213) || (208 == format)) { // 日期
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                double value = cell.getNumericCellValue();
                Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(value);
                if (date == null || "".equals(date)) {
                    return "";
                }
                return sdf.format(date);

            } else { // 不是日期格式
                cell.setCellType(Cell.CELL_TYPE_STRING);
            }
        }
        // 判断数据的类型
        switch (cell.getCellType()) {
            // 数字
            case Cell.CELL_TYPE_NUMERIC:
                cellValue = String.valueOf(cell.getNumericCellValue());
                break;
            // 字符串
            case Cell.CELL_TYPE_STRING:

                cellValue = String.valueOf(cell.getStringCellValue()).trim().replaceAll(String.valueOf((char) 10), "")
                        .replaceAll(String.valueOf((char) 11), "").replaceAll(String.valueOf((char) 12), "")
                        .replaceAll(String.valueOf((char) 13), "");
                break;
            // 布尔
            case Cell.CELL_TYPE_BOOLEAN:
                cellValue = String.valueOf(cell.getBooleanCellValue());
                break;
            // 公式
            case Cell.CELL_TYPE_FORMULA:
//                cellValue = String.valueOf(cell.getCellFormula());
                try {
                    cellValue = String.valueOf(cell.getNumericCellValue());
                } catch (IllegalStateException e) {
                    cellValue = String.valueOf(cell.getRichStringCellValue());
                }
                break;
            // 空
            case Cell.CELL_TYPE_BLANK:
                cellValue = "";
                break;
            // 错误
            case Cell.CELL_TYPE_ERROR:
                cellValue = "非法字符";
                break;
            default:
                cellValue = "未知类型";
                break;
        }
        return cellValue;
    }
}

service注入一个上传类:

	@Autowired
	private UploadManager uploadManager;

上传工具类(拷贝即用):



import com.yogapay.core.LangUitls;
import com.yogapay.sql.mapping2.StringListSQLData;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

public class UploadManager implements InitializingBean {

	public static final String PATH_PREFIX = "/uploads";
	private final String basePath;
	private final String[] dirNames;
	@Autowired(required = false)
	private ServletContext sc;
	//
	private File baseDir;
	private URI baseDirUri;
	private Map<String, File> dirs;

	public UploadManager(String basePath, String dirNames) {
		this.basePath = StringUtils.trimToNull(basePath);
		this.dirNames = dirNames.split("\\s+");
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		if (sc == null) {
			baseDir = new File("target");
		} else {
			baseDir = new File(basePath == null ? sc.getRealPath("uploads") : basePath);
		}
		baseDirUri = baseDir.toURI();
		dirs = new HashMap<String, File>();
		for (String dir : dirNames) {
			dirs.put(dir, createDir(dir));
		}
		dirs = Collections.unmodifiableMap(dirs);
	}

	private File createDir(String name) {
		File t = new File(baseDir, name);
		if (!t.mkdir() && !t.exists()) {
			throw new RuntimeException(t.getAbsolutePath());
		}
		return t;
	}

	public File file(String src) {
		if (!src.startsWith(PATH_PREFIX)) {
			throw new IllegalArgumentException();
		}
		src = src.substring(PATH_PREFIX.length());
		if (src.isEmpty() || src.charAt(0) != '/') {
			throw new IllegalArgumentException();
		}
		return new File(baseDirUri.resolve(src.substring(1)));
	}

	public String src(File f) {
		URI uri = baseDirUri.relativize(f.toURI());
		if (uri.isAbsolute()) {
			throw new IllegalArgumentException();
		}
		return PATH_PREFIX + "/" + uri;
	}

	public StringListSQLData saveDailyFiles(File rdir, Date date, MultipartFile[] files, String prefix, String suffix) throws IOException {
		if (files == null) {
			return null;
		}
		File dir = LangUitls.dailyFile(rdir, date);
		StringListSQLData fileList = new StringListSQLData();
		for (MultipartFile img : files) {
			if (!img.isEmpty()) {
				File f = File.createTempFile(prefix, suffix, dir);
				img.transferTo(f);
				fileList.add(src(f));
			}
		}
		return fileList;
	}

	public File getBaseDir() {
		return baseDir;
	}

	public Map<String, File> getDirs() {
		return dirs;
	}

}

StringListSQLData:
public class StringListSQLData extends ArrayList<String> implements SQLDataConvertible {

	public StringListSQLData(int initialCapacity) {
		super(initialCapacity);
	}

	public StringListSQLData() {
	}

	public StringListSQLData(Collection<? extends String> c) {
		super(c);
	}

	@Override
	public void toSQLData(PreparedStatement pstmt, int index) throws SQLException {
		Element eArray = DocumentHelper.createElement("List");
		for (String t : this) {
			Element eValue = DocumentHelper.createElement("value");
			eValue.setText(t == null ? "" : t);
			eArray.add(eValue);
		}
		pstmt.setString(index, eArray.asXML());
	}

	@Override
	public boolean fromSQLData(ResultSet rs, int index) throws SQLException {
		String xml = rs.getString(index);
		if (rs.wasNull()) {
			return false;
		}
		try {
			Document doc = DocumentHelper.parseText(xml);
			for (Iterator<Element> iterator = doc.getRootElement().elementIterator("value"); iterator.hasNext();) {
				Element next = iterator.next();
				this.add(next.getText());
			}
		} catch (DocumentException ex) {
			throw new SQLException("\r\n" + xml, ex);
		}
		return true;
	}

获取文件地址:

	public String getFilePath(MultipartFile file) throws IOException {
		MultipartFile[] files = {file};
		String targetDir = uploadManager.getBaseDir() + "/" + "";
		int index = file.getOriginalFilename().lastIndexOf(".");
		String ext = index > 0 ? file.getOriginalFilename().substring(index + 1) : "";
		StringListSQLData fileData = uploadManager.saveDailyFiles(new File(targetDir), new Date(), files, "file_", "." + ext);
		return fileData.get(0);
	}

最后在Mybatis中将对应映射的sql写好就行了哦

	<insert id="importAnnualDemand" >
		INSERT IGNORE INTO 表名(字段名)
		VALUES
		<foreach item="i" collection="list" separator=",">(#{i.属性名})</foreach>
	</insert>

最后导入成功:

今天的分享结束啦,谢谢大家哦~~

有关java-文件上传-excel存入数据库全代码及流程(附前端代码)的更多相关文章

  1. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  2. ruby - 其他文件中的 Rake 任务 - 2

    我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时

  3. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  4. ruby-on-rails - Rails 3 中的多个路由文件 - 2

    Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

  5. ruby - 将差异补丁应用于字符串/文件 - 2

    对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl

  6. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  7. ruby - 如何在 buildr 项目中使用 Ruby 代码? - 2

    如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby​​

  8. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  9. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

    使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

  10. ruby-on-rails - Rails 源代码 : initialize hash in a weird way? - 2

    在rails源中:https://github.com/rails/rails/blob/master/activesupport/lib/active_support/lazy_load_hooks.rb可以看到以下内容@load_hooks=Hash.new{|h,k|h[k]=[]}在IRB中,它只是初始化一个空哈希。和做有什么区别@load_hooks=Hash.new 最佳答案 查看rubydocumentationforHashnew→new_hashclicktotogglesourcenew(obj)→new_has

随机推荐