java文件的上传操作

来源:互联网 发布:汇顶科技 待遇知乎 编辑:程序博客网 时间:2024/05/27 20:03

对于文件上传到服务器,这个是我们日常生活中常见的操作,今天自己写代码测试了一下,仅供参考

首先,对于文件上传我们需要两个jar包:commons-fileupload-1.2.1.jar 和 commons-io-2.4.jar

上传文件的大致思路就是,先获取该文件的输入流,然后调用write()方法,将输入流写到你要保存的位置即可

第一步,封装了一个文件属性的类FileBean:

package com;import javax.activation.DataHandler;import javax.xml.bind.annotation.XmlAccessType;import javax.xml.bind.annotation.XmlAccessorType;import javax.xml.bind.annotation.XmlMimeType;import javax.xml.bind.annotation.XmlRootElement;/** * 文件属性封装 * @ClassName: File * @Description: TODO * @author FishRoad *  * */@XmlRootElement  @XmlAccessorType(XmlAccessType.FIELD)public class FileBean {/** * 文件名 */private String fileName;  /** * 文件类型 */    private String fileType;    /**     * 位置     */    private long position;    /**     * 字节数组     */    private byte[] bytes;        @XmlMimeType("application/octet-stream")    private DataHandler handler;    public String getFileName() {return fileName;}public void setFileName(String fileName) {this.fileName = fileName;}public String getFileType() {return fileType;}public void setFileType(String fileType) {this.fileType = fileType;}public long getPosition() {return position;}public void setPosition(long position) {this.position = position;}public byte[] getBytes() {return bytes;}public void setBytes(byte[] bytes) {this.bytes = bytes;}public DataHandler getHandler() {return handler;}public void setHandler(DataHandler handler) {this.handler = handler;}}

然后,我们就可以来写上传文件的代码了,创建了一个名为FileUpLoad的类:

package com;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.nio.channels.FileChannel;import javax.activation.DataHandler;import javax.activation.FileDataSource;public class FileUpLoad {// 上传文件的保存路径public static String basepath = "D:/WEB-INF";public static void main(String[] args) {// 自己写的工具类,获取文件的路径:// 例如:C:\Users\Administrator\Documents\导出个性化单据\邮银财富·债券2014年第240期产品成立参数表.xlsString path = UtilTools.getDirPath();// 创建文件对象FileBean fileBean = new FileBean();System.out.println(path);//通过文件的路径信息,获取文件的名称fileBean.setFileName(path.substring(path.lastIndexOf("\\") + 1,path.lastIndexOf(".")));System.out.println(fileBean.getFileName());//获取文件的类型fileBean.setFileType(path.substring(path.lastIndexOf(".") + 1));System.out.println(path.substring(path.lastIndexOf(".") + 1));//创建引用指定 DataSource 的 DataHandler 实例。数据以字节流的形式存在。DataSource 将提供一个 InputStream 来访问数据。 fileBean.setHandler(new DataHandler(new FileDataSource(path)));//获取文件的大小Klong fileSize = getFileSize(path);System.out.println(fileSize);try {//上传文件String destpath = uploadFile(fileBean);System.out.println(destpath);} catch (IOException e) {System.out.println("文件上传失败!");}}/** * 上传文件到服务器硬盘上 *  * @param filebean * @return * @throws IOException */public static String uploadFile(FileBean filebean) throws IOException {OutputStream os = null;InputStream is = null;File file = null;try {file = new File(basepath + "/" + filebean.getFileName() + "."+ filebean.getFileType() + ".tmp");os = new FileOutputStream(file);is = filebean.getHandler().getInputStream();byte[] bytes = new byte[1024];int len = 0;while ((len = is.read(bytes)) != -1) {os.write(bytes, 0, len);os.flush();}} catch (IOException e) {if (file.exists()) {file.delete();}throw e;} finally {try {if (os != null)os.close();} catch (IOException e) {}try {if (is != null)is.close();} catch (IOException e) {}}File _f = getUniqFile(filebean.getFileName(), filebean.getFileType(), 0);if (file != null && file.exists()) {if (file.renameTo(_f)) {return _f.getPath();} else {return null;}}return null;}/** * 如果上传的文件名重复了,则在新的文件后面加上序号 *  * @param fileName * @param fileType * @param idx * @return */private static File getUniqFile(String fileName, String fileType, int idx) {File _file = null;if (idx == 0) {_file = new File(basepath + "/" + fileName + "." + fileType);} else {_file = new File(basepath + "/" + fileName + "(" + idx + ")."+ fileType);}if (_file.exists()) {_file = getUniqFile(fileName, fileType, idx + 1);}return _file;}/** * 根据文件的绝对路径获取文件的大小(K) *  * @param path * @return */private static long getFileSize(String path) {long size = 0;File _file = new File(path);if (!_file.exists()) {return 0;}FileInputStream is = null;try {is = new FileInputStream(_file);FileChannel ch = is.getChannel();size = ch.size();} catch (IOException ex) {System.out.println("获取文件大小出错!");} finally {try {if (is != null)is.close();} catch (IOException ex) {}}return size;}}

获取文件路径的工具类方法:

/** * swing页面形式的选择文件存储位置 *  * @return */public static String getDirPath() {JFileChooser parseDir = new JFileChooser();parseDir.setAcceptAllFileFilterUsed(true);parseDir.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);int result = parseDir.showOpenDialog(null);if (result == JFileChooser.APPROVE_OPTION) {System.out.println(parseDir.getSelectedFile().getAbsolutePath());return parseDir.getSelectedFile().getAbsolutePath();} else {return "";}}



0 0
原创粉丝点击