精华内容
下载资源
问答
  • JAVA文件上传工具类

    千次阅读 2014-06-26 11:33:39
    package com.ccxe.trust.proselect.action; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; impo
    package com.ccxe.trust.proselect.action;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.InputStream;
    import java.io.PrintWriter;
    import java.io.UnsupportedEncodingException;
    import java.net.URLEncoder;
    import java.util.List;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import net.sf.json.JSONArray;
    import net.sf.json.JSONObject;
    
    import org.apache.log4j.Logger;
    import org.apache.struts2.ServletActionContext;
    import org.springframework.web.context.ContextLoader;
    import org.springframework.web.context.WebApplicationContext;
    
    import com.ccxe.common.util.FileUtil;
    import com.ccxe.common.util.StringUtil;
    import com.ccxe.common.web.BaseAction;
    import com.ccxe.trust.proselect.pojo.BAtta;
    import com.ccxe.trust.proselect.service.IProSelectCommonService;
    import com.ccxe.trust.proselect.util.ProConstants;
    import com.ccxe.trust.proselect.util.TrustConfig;
    
    /**
     * 附件上传Action
     * 
     * 
     * Dec 3, 2013
     */
    public class AttachmentUploadAction extends BaseAction {
    
    	private static final long serialVersionUID = 1L;
    	private Logger log = Logger.getLogger(AttachmentUploadAction.class);
    	private IProSelectCommonService proSelectCommonService;
    	
    	private File[] upload;// 实际上传文件
    	private String[] uploadContentType; // 文件的内容类型
    	private String[] uploadFileName; // 上传文件名
    	private List<String> attType;
    	private BAtta attachment;
    	//错误信息
    	private String msg = "";
    	
    	/**
    	 * 响应操作:上传各项附件
    	 */
    	public String upload() {
    		try {
    			JSONArray array = new JSONArray();
    			JSONObject json = null;
    			if(null != upload) {
    				for(int i = 0;i<upload.length;i++) {
    					if(this.upload[i].length() < ProConstants.FILE_SIZE) {
    						if(this.proSelectCommonService.checkAttachment(attachment.getRelaId(), attachment.getAttCata(), attType.get(i)) == 0){
    							BAtta att = null;
    							String ioFileName = FileUtil.writerFile(upload[i],uploadFileName[i]);
    							if(StringUtil.isNotNull(ioFileName)) {
    								att = new BAtta();
    								att.setRelaId(attachment.getRelaId());
    								att.setAttTitle(uploadFileName[i]);
    								att.setAttSrcTitle(uploadFileName[i]);
    								att.setAttCata(attachment.getAttCata());
    								att.setAttPath(ioFileName);
    								att.setAttType(attType.get(i));
    								att.setStatus(ProConstants.DC_BL_STATUS.BOOL_YES);
    								att.setCreateUser(this.getSessionUserInfo().getUserID());
    								att.setUpdateUser(this.getSessionUserInfo().getUserID());
    								att.setAttSeqNum(i+1);
    								this.getProSelectCommonService().saveProAttachment(att);
    							}
    						}else {  //此类别附件已存在
    							json = new JSONObject();
    							json.put("msg","【" + attType.get(i) + "】附件已存在,可以删除以后再上传.");
    							array.add(json);
    						}
    					}else {   //上传文件大于限制大小
    						json = new JSONObject();
    						json.put("msg", "【" + attType.get(i) + "】上传文件超过系统限制" + ProConstants.FILE_SIZE / (1024*1024) + "M.");
    						array.add(json);
    					}
    				}
    			}
    			msg = array.size() > 0 ? java.net.URLEncoder.encode(array.toString(),"UTF-8"): "";
    		} catch (Exception e){
    			e.printStackTrace();
    			return INPUT;
    		}
    		return SUCCESS;
    	}
    
    	/**
    	 * 响应操作:删除附件
    	 * @return
    	 */
    	public String removeAttachment() {
    		PrintWriter out = null;
    		JSONObject json = new JSONObject();
    		try {
    			HttpServletResponse response = ServletActionContext.getResponse();
    			response.setContentType("text/html;charset=UTF-8");
    			out = response.getWriter();
    			
    			String attId = (String)this.getAppRequestParameterByName("attId");
    			if(StringUtil.isNotNull(attId)) {
    				this.proSelectCommonService.deleteProAttachment(attId);
    			}
    			json.put("status","success");
    			json.put("id", attId);
    			out.print(json.toString());
    		}catch(Exception e) {
    			log.error("删除附件出错",e);
    			json.put("status","error");
    			out.print(json.toString());
    		}finally {
    			if (out != null) {
    				out.flush();
    				out.close();
    			}
    		}
    		return null;
    	}
    	
    	private String fileName;// 初始的通过param指定的文件名属性    
        private String inputPath;// 指定要被下载的文件路径
    	/**
    	 * 响应操作:下载附件
    	 * @return
    	 */
        public String download() {
        	try{
        		WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
    			TrustConfig  trustConfig =  (TrustConfig)wac.getBean(ProConstants.configBeanName);//模块配置文件
    			String attId = (String)this.getAppRequestParameterByName("attId");
    			if(StringUtil.isNotNull(attId)) {
    				this.attachment = this.getProSelectCommonService().fetchAttachment(attId);
    				if(null != attachment) {
    					//inputPath =  trustConfig.getTrustProselectCustFilePath()+"/" +attachment.getAttPath();
    					inputPath =  trustConfig.getTrustProselectCustFilePath()+ attachment.getAttPath();//20140528 zhaocg modified:配置文件中统一加了/
    					//fileName = java.net.URLEncoder.encode(attachment.getAttSrcTitle(),"UTF-8");
    					fileName = attachment.getAttSrcTitle();
    				}
    			}
        		File file = new File(inputPath);
        		if(!file.exists()) {
        			this.getAppRequest().setAttribute("errorMsg","下载的附件不存在或已被删除。");
        			return ERROR;
        		}
        	}catch(Exception e){
        		log.error("下载附件出错",e);
        		return ERROR;
        	}
        	return SUCCESS;
        }
        public String getDownloadFileName() {
    		String downFileName = fileName;
    		try {
    			HttpServletRequest request = getAppRequest();
    			String agent = request.getHeader("USER-AGENT");
    			if(null != agent && -1 != agent.indexOf("theworld")){	//世界之窗
    				downFileName = new String(downFileName.getBytes("gb2312"), "ISO8859-1");    //解决下载的文件名中含有小括号转变义符%28%29
    			}else if(null != agent && -1 != agent.indexOf("MSIE 8.0")){	//IE8
    				//downFileName = java.net.URLDecoder.decode(downFileName,"UTF-8");
    				downFileName =URLEncoder.encode(downFileName, "UTF-8").replace("+","%20"); 
    			}else if(null != agent && -1 != agent.indexOf("MSIE 7.0") && -1 != agent.indexOf("SE 2.X MetaSr 1.0")){	//sogo浏览器
    				downFileName =URLEncoder.encode(downFileName, "UTF-8").replace("+","%20"); 
    			}else if(null != agent && (-1 != agent.indexOf("SV1") || -1 != agent.indexOf("360SE"))){	//360安全浏览器
    				downFileName = new String(downFileName.getBytes("gb2312"), "ISO8859-1"); 
    			}else if(null != agent && -1 != agent.indexOf("Chrome")){	//google
    				//fileName = URLEncoder.encode(downFileNameCN,"UTF-8").replace("+","%20");	
    				downFileName = new String(downFileName.getBytes("gb2312"), "ISO8859-1"); //解决下载的文件名中含有小括号转变义符%28%29
    			}else if(null != agent && -1 != agent.indexOf("Firefox")){	//Firefox
    				//downFileName = java.net.URLDecoder.decode(downFileName,"UTF-8");
    				downFileName = new String(downFileName.getBytes("gb2312"), "ISO8859-1");
    			}else if(null != agent && -1 != agent.indexOf("Safari")){	//Safari 
    				downFileName = new String(downFileName.getBytes("UTF-8"), "ISO8859-1");
    			}else if(null != agent && -1 != agent.indexOf("Opera")){	//Opera
    				downFileName = new String(downFileName.getBytes("UTF-8"), "ISO8859-1");
    			}else {	//其它浏览器
    				downFileName = new String(downFileName.getBytes("gb2312"), "ISO8859-1");
    			}
    		}catch(UnsupportedEncodingException e) {    
               e.printStackTrace();    
    		}    
    		return downFileName;
        }
    	public InputStream getInputStream() throws Exception {
        	InputStream inputStream = new FileInputStream(new File(inputPath));
        	return inputStream;
        }
    	public File[] getUpload() {
    		return upload;
    	}
    	public void setUpload(File[] upload) {
    		this.upload = upload;
    	}
    	public String[] getUploadContentType() {
    		return uploadContentType;
    	}
    	public void setUploadContentType(String[] uploadContentType) {
    		this.uploadContentType = uploadContentType;
    	}
    	public String[] getUploadFileName() {
    		return uploadFileName;
    	}
    	public void setUploadFileName(String[] uploadFileName) {
    		this.uploadFileName = uploadFileName;
    	}
    	public List<String> getAttType() {
    		return attType;
    	}
    	public void setAttType(List<String> attType) {
    		this.attType = attType;
    	}
    	public BAtta getAttachment() {
    		return attachment;
    	}
    	public void setAttachment(BAtta attachment) {
    		this.attachment = attachment;
    	}
    	public IProSelectCommonService getProSelectCommonService() {
    		return proSelectCommonService;
    	}
    	public void setProSelectCommonService(
    			IProSelectCommonService proSelectCommonService) {
    		this.proSelectCommonService = proSelectCommonService;
    	}
    	public String getMsg() {
    		return msg;
    	}
    	public void setMsg(String msg) {
    		this.msg = msg;
    	}
    }
    
    <!-- 附件 -->
    		<action name="att_*" class="com.ccxe.trust.proselect.action.AttachmentUploadAction" method="{1}">
    			<result type="redirect">/proSelect/proSetup_fetchProAtt.action?proId=${attachment.relaId}&msg=${msg}</result>
    		</action>
    		<!-- 附件下载 -->
    		<action name="downloadAtt" class="com.ccxe.trust.proselect.action.AttachmentUploadAction" method="download">  
    	            <param name="inputPath">${inputPath}</param>  
    	            <!-- 初始文件名 -->  
    	            <param name="fileName">${fileName}</param>  
    	            <result name="success" type="stream">  
    	                <param name="contentType">application/octet-stream;charset=UTF-8</param>  
    	                <param name="inputName">inputStream</param>  
    	                <!-- 使用经过转码的文件名作为下载文件名,downloadFileName属性对应action类中的方法 getDownloadFileName() -->  
    	                <param name="contentDisposition">attachment;filename="${downloadFileName}"</param>  
    	                <param name="bufferSize">4096</param>  
    	            </result>
            </action>


    展开全文
  • java文件上传工具类

    千次阅读 2018-10-30 11:23:02
    import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; ...

    package util;


    import java.awt.image.BufferedImage;
    import java.io.ByteArrayInputStream;
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;


    import javax.imageio.ImageIO;


    import org.apache.commons.io.FileUtils;
    import org.springframework.web.multipart.MultipartFile;


    import sun.misc.BASE64Decoder;


    /**
     * 上传文件
     * 
     */
    public class FileUpload {


    /**
    * @param file
    *            //文件对象
    * @param filePath
    *            //上传路径
    * @param fileName
    *            //文件名
    * @return 文件名
    */
    public static String fileUp(MultipartFile file, String filePath, String fileName) {
    String extName = ""; // 扩展名格式:

    File file2 = new File(filePath);
    // 如果文件夹不存在则创建
    if (!file2.exists() && !file2.isDirectory()) {
    System.out.println(filePath + "//不存在");
    file2.mkdir();
    }


    try {
    if (file.getOriginalFilename().lastIndexOf(".") >= 0) {
    extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
    }
    copyFile(file.getInputStream(), filePath, fileName + extName).replaceAll("-", "");
    } catch (IOException e) {
    System.out.println(e);
    }
    return fileName + extName;
    }


    public static String fileUpV2(String file, String filePath, String fileName) {
    String extName = ".png"; // 扩展名格式:
    try {


    BASE64Decoder decoder = new BASE64Decoder();
    // Base64解码
    byte[] b = decoder.decodeBuffer(file);
    for (int i = 0; i < b.length; ++i) {
    if (b[i] < 0) {// 调整异常数据
    b[i] += 256;
    }
    }
    InputStream inputStream = FileUpload.byte2Input(b);
    copyFile(inputStream, filePath, fileName + extName).replaceAll("-", "");
    } catch (IOException e) {
    System.out.println(e);
    }
    return fileName + extName;
    }


    public static InputStream fileUpV3(String file) {
    try {


    BASE64Decoder decoder = new BASE64Decoder();
    // Base64解码
    byte[] b = decoder.decodeBuffer(file);
    for (int i = 0; i < b.length; ++i) {
    if (b[i] < 0) {// 调整异常数据
    b[i] += 256;
    }
    }


    InputStream inputStream = new ByteArrayInputStream(b);
    return inputStream;
    } catch (IOException e) {
    System.out.println(e);
    }
    return null;
    }


    /**
    * 处理webp processWebp 处理webp (这里描述这个方法适用条件 – 可选) 标记:@param inputStream 标记:@param
    * file2 标记:@return 返回值:File 作者:brandon

    * @exception @since
    *                1.0.0
    */
    public static File processWebp(InputStream inputStream, String file2) {
    try {
    BufferedImage im = ImageIO.read(inputStream);
    File file = new File(file2);
    if (!file.exists()) {
    if (!file.getParentFile().exists()) {
    file.getParentFile().mkdirs();
    }
    file.createNewFile();
    }
    ImageIO.write(im, "webp", file);
    return file;
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    return null;
    }


    /**

    * processPng(这里用一句话描述这个方法的作用) (这里描述这个方法适用条件 – 可选) 标记:@param inputStream
    * 标记:@param file2 标记:@return 返回值:File 作者:brandon

    * @exception @since
    *                1.0.0
    */
    public static File processPng(InputStream inputStream, String file2) {
    try {
    BufferedImage im = ImageIO.read(inputStream);
    File file = new File(file2);
    if (!file.exists()) {
    if (!file.getParentFile().exists()) {
    file.getParentFile().mkdirs();
    }
    file.createNewFile();
    }
    ImageIO.write(im, "png", file);
    return file;
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    return null;
    }


    /**

    * processPng(这里用一句话描述这个方法的作用) (这里描述这个方法适用条件 – 可选) 标记:@param im 标记:@param file2
    * 标记:@return 返回值:File 作者:brandon

    * @exception @since
    *                1.0.0
    */
    public static File processPng(BufferedImage im, String file2) {
    try {
    File file = new File(file2);
    if (!file.exists()) {
    if (!file.getParentFile().exists()) {
    file.getParentFile().mkdirs();
    }
    file.createNewFile();
    }
    ImageIO.write(im, "png", file);
    return file;
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    return null;
    }


    /**

    * byte2Input(这里用一句话描述这个方法的作用) (这里描述这个方法适用条件 – 可选) 标记:@param buf 标记:@return
    * 返回值:InputStream 作者:brandon

    * @exception @since
    *                1.0.0
    */
    public static final InputStream byte2Input(byte[] buf) {
    return new ByteArrayInputStream(buf);
    }


    /**
    * 写文件到当前目录的upload目录中

    * @param in
    * @param fileName
    * @throws IOException
    */
    private static String copyFile(InputStream in, String dir, String realName) throws IOException {
    File file = new File(dir, realName);
    System.out.println("copy file before================= " + dir);
    if (!file.exists()) {
    System.out.println("copy file path not exist================= " + dir);
    if (!file.getParentFile().exists()) {
    file.getParentFile().mkdirs();
    }
    file.createNewFile();
    }
    FileUtils.copyInputStreamToFile(in, file);
    return realName;
    }


    public static InputStream returnBitMap(String path) {
    URL url = null;
    InputStream is = null;
    try {
    url = new URL(path);
    } catch (MalformedURLException e) {
    e.printStackTrace();
    }
    try {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 利用HttpURLConnection对象,我们可以从网络中获取网页数据.
    conn.setDoInput(true);
    conn.connect();
    is = conn.getInputStream(); // 得到网络返回的输入流


    } catch (IOException e) {
    e.printStackTrace();
    }
    return is;
    }


    /**

    * fileUpReturnFile(这里用一句话描述这个方法的作用) (这里描述这个方法适用条件 – 可选) 标记:@param file
    * 标记:@param filePath 标记:@param fileName 标记:@return 返回值:File 作者:brandon

    * @exception @since
    *                1.0.0
    */
    public static File fileUpReturnFile(MultipartFile file, String filePath, String fileName) {
    String extName = ""; // 扩展名格式:
    File result_file = null;
    try {
    if (file.getOriginalFilename().lastIndexOf(".") >= 0) {
    extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
    }
    result_file = copyFileReturnFile(file.getInputStream(), filePath, fileName + extName);
    } catch (IOException e) {
    System.out.println(e);
    }
    return result_file;
    }


    /**

    * copyFileReturnFile(这里用一句话描述这个方法的作用) (这里描述这个方法适用条件 – 可选) 标记:@param in
    * 标记:@param dir 标记:@param realName 标记:@return 标记:@throws IOException 返回值:File
    * 作者:brandon

    * @exception @since
    *                1.0.0
    */
    private static File copyFileReturnFile(InputStream in, String dir, String realName) throws IOException {
    File file = new File(dir, realName);
    System.out.println("copy file before================= " + dir);
    if (!file.exists()) {
    System.out.println("copy file path not exist================= " + dir);
    if (!file.getParentFile().exists()) {
    file.getParentFile().mkdirs();
    }
    file.createNewFile();
    }
    FileUtils.copyInputStreamToFile(in, file);
    return file;
    }
    }

    展开全文
  • java文件上传下载工具类

    千次阅读 2019-06-14 18:24:41
    import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import jav...
    
    
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.io.OutputStream;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    /**
     * <b>
     * </b><br><br><i>Description</i> :
     * <br> Author : dxl
     * <br> Date : 2019/1/9 11:08
     */
    public class DxlFileUtil {
    
        /**
         * 单个文件上传
         * @param
         * @param fileName
         * @param filePath
         */
        public static void upFile(File uploadFile,String fileName,String filePath){
    
            FileOutputStream fos = null;
            BufferedOutputStream bos = null;
            FileInputStream is = null;
            BufferedInputStream bis = null;
            File file = new File(filePath);
            if(!file.exists()){
                file.mkdirs();
            }
            File f = new File(filePath+"/"+fileName);
            try {
                is = new FileInputStream(uploadFile);
                bis = new BufferedInputStream(is);
                fos = new FileOutputStream(f);
                bos = new BufferedOutputStream(fos);
                byte[] bt = new byte[4096];
                int len;
                while((len = bis.read(bt))>0){
                    bos.write(bt, 0, len);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
    
                try {
                    if(null != bos){
                        bos.close();
                        bos = null;}
                    if(null != fos){
                        fos.close();
                        fos= null;
                    }
                    if(null != is){
                        is.close();
                        is=null;
                    }
    
                    if (null != bis) {
                        bis.close();
                        bis = null;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    
    
    
        /**
         * 单个文件上传
         * @param is
         * @param fileName
         * @param filePath
         */
        public static void upFile(InputStream is,String fileName,String filePath){
    
            FileOutputStream fos = null;
            BufferedOutputStream bos = null;
            BufferedInputStream bis = null;
            File file = new File(filePath);
            if(!file.exists()){
                file.mkdirs();
            }
            File f = new File(filePath+"/"+fileName);
            try {
                bis = new BufferedInputStream(is);
                fos = new FileOutputStream(f);
                bos = new BufferedOutputStream(fos);
                byte[] bt = new byte[4096];
                int len;
                while((len = bis.read(bt))>0){
                    bos.write(bt, 0, len);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
    
                try {
                    if(null != bos){
                        bos.close();
                        bos = null;}
                    if(null != fos){
                        fos.close();
                        fos= null;
                    }
                    if(null != is){
                        is.close();
                        is=null;
                    }
    
                    if (null != bis) {
                        bis.close();
                        bis = null;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    
    
    
    
    
    
    
    
        /**
         * @param request
         * @param response
         * @param downloadFile 下载文件完整路径
         * @param fileName 下载文件名(带文件后缀)
         */
        public static void downloadFile(HttpServletRequest request, HttpServletResponse response, String downloadFile, String fileName) {
    
            BufferedInputStream bis = null;
            InputStream is = null;
            OutputStream os = null;
            BufferedOutputStream bos = null;
            try {
                File file=new File(downloadFile); //:文件的声明
                is = new FileInputStream(file);  //:文件流的声明
                os = response.getOutputStream(); // 重点突出
                bis = new BufferedInputStream(is);
                bos = new BufferedOutputStream(os);
    
                if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) {
                    fileName = new String(fileName.getBytes("GB2312"),"ISO-8859-1");
                } else {
                    // 对文件名进行编码处理中文问题
                    fileName = java.net.URLEncoder.encode(fileName, "UTF-8");// 处理中文文件名的问题
                    fileName = new String(fileName.getBytes("UTF-8"), "GBK");// 处理中文文件名的问题
                }
    
                response.reset(); // 重点突出
                response.setCharacterEncoding("UTF-8"); // 重点突出
                response.setContentType("application/x-msdownload");// 不同类型的文件对应不同的MIME类型 // 重点突出
                // inline在浏览器中直接显示,不提示用户下载
                // attachment弹出对话框,提示用户进行下载保存本地
                // 默认为inline方式
                response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
                //  response.setHeader("Content-Disposition", "attachment; filename="+fileName); // 重点突出
                int bytesRead = 0;
                byte[] buffer = new byte[4096];// 4k或者8k
                while ((bytesRead = bis.read(buffer)) != -1){ //重点
                    bos.write(buffer, 0, bytesRead);// 将文件发送到客户端
                }
    
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                // 特别重要
                // 1. 进行关闭是为了释放资源
                // 2. 进行关闭会自动执行flush方法清空缓冲区内容
                try {
                    if (null != bis) {
                        bis.close();
                        bis = null;
                    }
                    if (null != bos) {
                        bos.close();
                        bos = null;
                    }
                    if (null != is) {
                        is.close();
                        is = null;
                    }
                    if (null != os) {
                        os.close();
                        os = null;
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
    
        /**
         * 文件下载
         * @param response
         * @param downloadFile 文件的路径
         * @param showFileName 下载后显示的文件名称
         */
        public static void downloadFile(HttpServletResponse response, String downloadFile, String showFileName) {
    
            BufferedInputStream bis = null;
            InputStream is = null;
            OutputStream os = null;
            BufferedOutputStream bos = null;
            try {
                File file=new File(downloadFile); //:文件的声明
                String fileName=file.getName();
                is = new FileInputStream(file);  //:文件流的声明
                os = response.getOutputStream(); // 重点突出
                bis = new BufferedInputStream(is);
                bos = new BufferedOutputStream(os);
                // 对文件名进行编码处理中文问题
                fileName = java.net.URLEncoder.encode(showFileName, "UTF-8");// 处理中文文件名的问题
                fileName = new String(fileName.getBytes("UTF-8"), "GBK");// 处理中文文件名的问题
                response.reset(); // 重点突出
                response.setCharacterEncoding("UTF-8"); // 重点突出
                response.setContentType("application/x-msdownload");// 不同类型的文件对应不同的MIME类型 // 重点突出
                // inline在浏览器中直接显示,不提示用户下载
                // attachment弹出对话框,提示用户进行下载保存本地
                // 默认为inline方式
                response.setHeader("Content-Disposition", "attachment; filename="+fileName); // 重点突出
                int bytesRead = 0;
                byte[] buffer = new byte[1024];
                while ((bytesRead = bis.read(buffer)) != -1){ //重点
                    bos.write(buffer, 0, bytesRead);// 将文件发送到客户端
                }
    
            } catch (Exception ex) {
                ex.printStackTrace();
                throw new RuntimeException(ex.getMessage());
            } finally {
                // 特别重要
                // 1. 进行关闭是为了释放资源
                // 2. 进行关闭会自动执行flush方法清空缓冲区内容
                try {
                    if (null != bis) {
                        bis.close();
                        bis = null;
                    }
                    if (null != bos) {
                        bos.close();
                        bos = null;
                    }
                    if (null != is) {
                        is.close();
                        is = null;
                    }
                    if (null != os) {
                        os.close();
                        os = null;
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    throw new RuntimeException(ex.getMessage());
                }
            }
        }
    
    }

     

    展开全文
  • Java实现文件上传下载工具类

    千次阅读 2017-10-10 08:52:54
    本篇文章在Eclipse环境下采用Java语言实现文件上传下载工具类。上传时,为避免文件名在服务器中重复,采用“服务器时间(定义到毫秒)+文件名+文件后缀“的方式作为服务器上的文件名;下载过程中利用 spring mvc ...

    本篇文章在Eclipse环境下采用Java语言实现文件上传下载工具类。上传时,为避免文件名在服务器中重复,采用“服务器时间(定义到毫秒)+文件名+文件后缀“的方式作为服务器上的文件名;下载过程中利用 spring mvc ResponseEntity 做文件下载,返回的是字节流,下载成功后可自定义文件的保存路径。具体源码如下所示:

    package com.utils;
    
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.UnsupportedEncodingException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    import org.apache.commons.io.FileUtils;
    import org.springframework.http.HttpHeaders;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.MediaType;
    import org.springframework.http.ResponseEntity;
    
    /**
     * 文件上传下载工具类
     * 
     */
    public class FileHelper {
    
        /**
         * 根据路径确定目录,没有目录,则创建目录
         * 
         * @param path
         */
        private static void createDir(String path) {
            File fileDir = new File(path);
            if (!fileDir.exists() && !fileDir.isDirectory()) {// 判断/download目录是否存在
                fileDir.mkdir();// 创建目录
            }
        }
    
        /**
         * 将文件名解析成文件的上传路径
         * 
         * @param fileName
         * @return 上传到服务器的文件名
         */
        public static String transPath(String fileName, String path) {
            createDir(path);
            Date date = new Date();
            SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMddhhmmssSSS");// 定义到毫秒
            String nowStr = dateformat.format(date);
            String filenameStr = fileName.substring(0, fileName.lastIndexOf("."));// 去掉后缀的文件名
            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);// 后缀
            if (fileName.trim() != "") {// 如果名称不为"",说明该文件存在,否则说明该文件不存在
                path += "\\" + filenameStr + nowStr + "." + suffix;// 定义上传路径
            }
            return path;
        }
    
        /**
         * 提醒文件下载
         * 
         * @param fileName
         * @param path
         * @return
         */
        public static ResponseEntity<byte[]> downloadFile(String fileName, String path) {
            try {
                fileName = new String(fileName.getBytes("GB2312"), "ISO_8859_1");// 避免文件名中文不显示
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }
            File file = new File(path);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", fileName);
    
            ResponseEntity<byte[]> byteArr = null;
            try {
                byteArr = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return byteArr;
        }
    
        /**
         * 将输入流中的数据写入字节数组
         * 
         * @param in
         * @return
         */
        public static byte[] inputStream2ByteArray(InputStream in, boolean isClose) {
            byte[] byteArray = null;
            try {
                int total = in.available();
                byteArray = new byte[total];
                in.read(byteArray);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (isClose) {
                    try {
                        in.close();
                    } catch (Exception e2) {
                        System.out.println("关闭流失败");
                    }
                }
            }
            return byteArray;
        }
    }
    
    展开全文
  • 文件上传可以使用 Apache 文件上传组件, commons-fileupload, 它依赖于 commons-io commons-io.jar: https://repo1.maven.org/maven2/commons-io/commons-io/2.6/commons-io-2.6.jar commons-fileupload: ...
  • Java工具类文件上传

    千次阅读 2016-09-26 11:09:21
    这里是一个文件上传工具类,通用性很强。废话不多说,直奔主题。如有疑问或错误,欢迎指正交流。   public class FileUploadUtils { private static final Logger logger = LoggerFactory.getLogger...
  • Java FTP上传文件工具类

    千次阅读 2016-07-11 14:38:53
    import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.net.InetSocketAddress; import java.util.Properties; import java
  • Java一个文件上传工具类

    千次阅读 2014-02-14 15:47:32
    * 文件上传 * * @author cary * @since 2012-12-19 下午2:22:12 */ public class FileUploader { static final String UPLOAD_PATH_KEY = "upload.dir"; private static Logger logger = Logger
  • java 上传文件到Linux服务器 工具类

    万次阅读 2017-06-06 10:09:35
    最近在帮同学做一个音乐推荐系统后台,需要java远程调用Linux服务器,执行深度学习算法,处理由本地上传文件。查找了相关的资料,利用ftpClient上传文件到服务器。在此贴一下这个助手(网上很多)。 import org....
  • Java文件操作工具类FileUtils

    万次阅读 2018-01-26 14:56:21
    java.nio.channels.ReadableByteChannel; import java.util.ArrayList; import java.util.List; public class FileUtils { /*判断文件是否存在*/ public static boolean isExists(String filePath) { ...
  • 文件上传工具类,服务器动态给客户端相应图片
  • Java文件压缩工具类ZipUtils学习笔记

    千次阅读 2018-08-19 07:51:23
    最近工作中用到了文件的压缩,经过在网上查询和自己的摸索总结如下工具了,支持文件压缩,嵌套文件压缩; package utils; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream...
  • 文件上传工具类及配置FastDFSUtils

    千次阅读 2018-06-08 11:45:23
    上传图片工具类import java.io.FileNotFoundException; import java.io.IOException; import org.apache.commons.io.FilenameUtils; import org.csource.common.NameValuePair; import org.csource.fastdfs....
  • -- Spring文件上传表单的视图解析器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="U
  • HDFSUtil ...将eclipse根目录下local.txt文件上传至HDFS 将HDFS系统中local.txt文件下载至eclipse根目录下 代码 package Utils; import java.io.BufferedInputStream; import java.io.File...
  • JAVA工具类(13)---图片上传工具类

    千次阅读 2017-09-10 21:19:11
    import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.*; ... * 图片上传工具类 * Created by charlin on 2017/9/10. */ public class UploadImageUtil { ...
  • 文件上传下载工具类java

    千次阅读 2018-09-14 11:27:07
    * @description : 文件上传util */ public class FileUtil { public static String uploadFile(byte[] file, String filePath, String fileName) throws Exception { File targetFile = new File(filePath); ...
  • Java 封装一个文件上传工具类

    千次阅读 2018-09-03 17:19:08
    package cn.itcast.utils; import java.util.UUID; public class UploadUtils { /** * 获取随机名称 * * @param realName 真实名称 * @return uuid */ public static String getUUIDName(S...
  • SpringBoot集成文件上传工具类

    千次阅读 2018-12-27 13:34:34
    log.info(" >>> 文件上传入口... ); List<UploadDto> list = new ArrayList(); if (multipartFile == null) { throw new CustomException(ResultEnum.OBJECT_IS_NULL.getCode(), ResultEnum.OBJECT_IS_NULL....
  • Java通过SSH实现文件上传下载功能实现 实现的主要功能: 1.上传 压缩对应的文件夹,生成临时文件.zip----&gt;上传临时文件.zip,上传成功,删除本地临时文件 ----&gt; 远程服务上解压到服务器指定路径,并...
  • 小编最近忙着学习项目构架上的一些技术,把实用的工具类整理下,单独放在一个项目。其他项目需要用直接使用maven依赖一下就可以使用了。项目中需要实现上传多张图片,由于多张图片,又担心并发量大。所以小编做了一...
  • 以http方式实现文件上传 工具类demo

    千次阅读 2013-11-30 15:14:55
    android 实现文件上传
  • FastDFS通过java实现文件上传与下载 1、资源准备 FastDFS安装配置请参考:https://blog.csdn.net/weixin_44187730/article/details/85951370 由于FastDFS客户端jar包并没有在中央仓库中,所以需要使用下列命令手动...
  • 为方便使用 封装了个工具类 1、如何获取密钥(AccessKey和SecretKey) 进入密钥管理: 查看AccessKey和SecretKey: 2、如何查看工作空间和存储区域: 3、为何要刷新文件 七牛云存储的文件默认是有缓存的 当删除之后...
  • SpringBoot 上传文件工具类的编写

    千次阅读 2019-07-16 18:04:29
    1.新建一个自动配置文件custom.properties并编写...2.编写读取配置文件工具类PropertiesUtil. package com.crawler.util; import java.io.IOException; import java.io.InputStream; import java.util.Propertie...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 99,856
精华内容 39,942
关键字:

java文件上传工具类

java 订阅