文件上传1

来源:互联网 发布:太阳能无网络监控器 编辑:程序博客网 时间:2024/05/16 01:53

这种方式可以上传图片,也可以上传音频文件,当然我写的代码,显得笨拙,不过功能上是有的,其实这样的代码在网上是随处可以见到的,我也参考的,在项目里应用

首先要有这两个jar包

commons-fileupload-1.3.jar和commons-io-1.2.jar包





=======================================servlet============================================

package com.cn.xiaw.reply.action;
import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.alibaba.fastjson.JSON;
import com.cn.xiaw.entry.Reply;
import com.cn.xiaw.entry.Talk;
import com.cn.xiaw.service.ReplyService;
import com.cn.xiaw.service.ReplyServiceImpl;
import com.cn.xiaw.service.TalkService;
import com.cn.xiaw.service.TalkServiceImpl;
import com.cn.xiaw.service.UserSerice;
import com.cn.xiaw.service.UserServiceImpl;
import com.cn.xiaw.util.CutPicture;
import com.cn.xiaw.util.HttpUtil;
import com.cn.xiaw.util.ImgUitl;
import com.cn.xiaw.util.PushOne;
public class InsertReplyAction extends HttpServlet {
    ReplyService replyservice = new ReplyServiceImpl();
    UserSerice userservice = new UserServiceImpl();
    TalkService talkservice=new TalkServiceImpl();
    @Override
    public void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/html");        
        try {                
            String qid=request.getParameter("qid");
            String uid=request.getParameter("uid");
            String fid=request.getParameter("fid");
            String uname=new String(request.getParameter("uname").getBytes("iso-8859-1"),"UTF-8");
            String content=new String(request.getParameter("content").getBytes("iso-8859-1"),"UTF-8");
            long otherid=Long.parseLong(request.getParameter("otherid"));
            String filepath=request.getParameter("filepath");            
            String othername=new String(request.getParameter("othername").getBytes("iso-8859-1"),"UTF-8");        
            Map <String,String> filemap = fileupdlod(request);    
            long time=new Date().getTime();            
            Reply reply=new Reply();
            reply.setQid(Long.parseLong(qid));
            reply.setFid(Long.parseLong(fid));
            reply.setContent(content);
            reply.setUid(Long.parseLong(uid));
            reply.setUname(uname);
            reply.setTime(new Timestamp(time));
            reply.setFilepath(filepath);
            reply.setOtherid(otherid);
            reply.setOthername(othername);
            reply.setReplyfilepath(filemap.get("replyfile"));
            reply.setVoicepath(filemap.get("replyvoicefile"));
            reply.setSmallreplyfilepath(filemap.get("smallreplyfile"));        
            long counts=replyservice.addReplyjdbc(reply);//    
        /*    String devicetoken=userservice.getDevicetoken(otherid);//获取的是要发送的设备token    
            Map<String, Object> map0 = new HashMap<String, Object>();    
            map0.put("qid", qid);
            map0.put("rid", "");            
            map0.put("type", 0);//0表示对问题的直接回答
             String text=    JSON.toJSONString(map0).toString();
            //此时要发送消息一条                    
            PushOne pushone=new PushOne(devicetoken,(int)counts, text);
            pushone.start();*/
            Map<String, Object> map = new HashMap<String, Object>();
            if(counts==0){
                map.put("message", "false");
            }else{
            map.put("message", "success");
            }
            HttpUtil.http(map, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }    
    public Map <String,String> fileupdlod(HttpServletRequest request) {
        Map <String,String>map=new HashMap<String,String>();
        String str = "";
        String smallstr = "";//缩略图
        // 为解析类提供配置信息
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 创建解析类的实例
        ServletFileUpload sfu = new ServletFileUpload(factory);
        // 开始解析
        sfu.setFileSizeMax(-1);
        // 每个表单域中数据会封装到一个对应的FileItem对象上
        try {
            List<FileItem> items = sfu.parseRequest(request);
            UUID uuidp = UUID.randomUUID();
            // 区分表单域
            for (int i = 0; i < items.size(); i++) {
                FileItem item = items.get(i);
                // isFormField为true,表示这不是文件上传表单域
                if (!item.isFormField()) {
                    ServletContext sctx = getServletContext();
                    // 获得存放文件的物理路径
                    UUID uuid = UUID.randomUUID();
                    // upload下的某个文件夹 得到当前在线的用户 找到对应的文件夹
                    String paths = sctx.getRealPath("/reply");                    
                    File file = new File(paths+"/"+uuidp);
                    file.mkdirs();
                    File file1 = new File(paths+"/"+uuidp+"/1");
                    file1.mkdirs();
                
                    
                    // 获得文件名
                    String fileName = item.getName();                    
                    String fi = fileName.replace("E:", "");
                    // 该方法在某些平台(操作系统),会返回路径+文件名            
                    String[] fileNames = fi.split("\\.");
                    if (fileNames.length > 1) {
                        fi = uuid + "." + fileNames[1];
                        fileName = fi.substring(fi.lastIndexOf("/") + 1);
                        File files = new File(paths+"/"+uuidp + "/" + fileName);
                        if (!files.exists()) {
                            if(!fileName.contains("caf")){
                            item.write(files);
                            str = pinjie(str, "reply/"+uuidp + "/" + fileName);
                            map.put("replyfile", str);
                            ImgUitl.makeSamll(files,paths+ "/"+uuidp + "/" + fileName,640);//生成缩略图-----给定缩略图的高100,按照原比例大小来生成新图片
                            ImgUitl.makeSamll(files, paths+"/"+uuidp+"/1/"+fileName,250);//生成缩略图
                            smallstr = pinjie(smallstr, "reply/"+uuidp + "/1/" + fileName);
                            //    ImgUitl.makeSamll(files, paths+"/"+uuidp+"/1/2/"+fileName,84);//生成缩略图-----给定缩略图的高100,按照原比例大小来生成新图片
                            CutPicture.cutCenterImage( paths+"/"+uuidp+"/1/"+fileName,  paths+"/"+uuidp+"/1/"+fileName, 250, 250);
                            map.put("smallreplyfile", smallstr);
                            }else {
                                File voicefile = new File(paths+"/voice/"+uuidp);
                                voicefile.mkdirs();
                                File voicefiles = new File(paths+"/voice/"+uuidp+ "/" + fileName);
                                item.write(voicefiles);
                                map.put("replyvoicefile", "reply/voice/"+uuidp+ "/" + fileName);    
                            }    
                        }
                    }
                }
            }
        } catch (Exception e) {
        }
        return map;
    }
    public String pinjie(String str, String filename) {    
        if (!str.equals("")) {
            str = str + "%" + filename;
        }else     if (str.equals("")) {
            str = filename;
        }
        return str;
    }
}

WEB.XML配置就不粘了

===========================================JSP==============================================================================

 <div  style="display: ;height: 30px" >
<form action="../Xiawan_01/fileupload?id=<%=ids %>" method="post" enctype="multipart/form-data">
<input type="file" name="filename">
<input type="submit" value="上传"  id="sub1">
</form>

其实上面的jar就是按着这样的jsp页面上提交form表单的原理开发的enctype="multipart/form-data" 而苹果手用他的传送数据方式,同样可以接受,我这里就是和苹果手机对接的程序,而jsp页面的上传form,仅仅是一个简单的测试而已





0 0
原创粉丝点击