音乐服务器项目中登录及上传视频、音乐等的代码记录

项目小结 专栏收录该内容
2 篇文章 0 订阅


前言

近期完成了一个小小的音乐服务器的项目,就是上传音乐和视频,可以用户登录,添加喜欢和删除等功能


一、贴一些代码片段做小结

登录


import Service.UserService;
import entity.User;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

@WebServlet("/login")
public class loginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset = utf-8");
        UserService service = new UserService();
        Map<String, Object> return_map = new HashMap<>();
            //1.获取请求中的用户名 密码
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            if (username == null || " ".equals(username) || password == null || " ".equals(password)) {
                return_map.put("msg", false);
                return;
            }
            //2.创建一个数据库实体类对象
            User user = new User();
            user = service.selectByName(username);
            boolean isLogin = service.login(user);
            if (isLogin) {
                HttpSession session = req.getSession(true);//创建会话 绑定数据
                session.setAttribute("user", user);
                return_map.put("msg", true);
            } else {
                return_map.put("msg", false);//返回登录错误的信息
            }
        ObjectMapper mapper = new ObjectMapper();
        //利用Jackson 将map转化为json对象
        //writer 将转换后的json 字符串保存到字符输出流中,最后给客户端
        mapper.writeValue(resp.getWriter(), return_map);

    }
}



上传音乐

import Service.MusicService;
        import com.fasterxml.jackson.databind.ObjectMapper;
        import entity.Music;
        import entity.User;

        import javax.servlet.ServletException;
        import javax.servlet.annotation.MultipartConfig;
        import javax.servlet.annotation.WebServlet;
        import javax.servlet.http.HttpServlet;
        import javax.servlet.http.HttpServletRequest;
        import javax.servlet.http.HttpServletResponse;
        import javax.servlet.http.Part;
        import java.io.IOException;
        import java.util.HashMap;

@WebServlet("/upload")
@MultipartConfig
public class UploadMusicServlet extends HttpServlet {
    private static final String SAVEPATH = "C:\\Users\\16334\\IdeaProjects\\onlineListenPlayer\\src\\main\\webapp\\music\\";//后面按两个斜杠表示要往这个后面放  这是自己创建的要放上传音乐的目录
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        User user = (User) req.getSession().getAttribute("user");
        HashMap<String,Object> map = new HashMap<>();
        if(user==null){
            System.out.println("请登陆后上传");
            map.put("msg",false);
        }else {
            Part part  =req.getPart("filename");
            String header = part.getHeader("Content-Disposition");
            int start = header.lastIndexOf("=");
            String fileName = header.substring(start+1).replace("\"","");
            System.out.println("fileName " +fileName);
            //写入part文件中
            part.write(SAVEPATH+fileName);
            String singer = req.getParameter("singer");
            // System.out.println("歌手:"+singer);
            //写入数据库
            String[] titles = fileName.split("\\.");//成都.MP3  去除点号  成都 0 下标
            String title = titles[0]; //不需要.MP3后缀  因为音乐默认都是MP3
            //   System.out.println("title:" + title);
            String url = "music/"+title;
            //  System.out.println("url:"+url);

            MusicService service = new MusicService();
            int userId = user.getId();
            Music music = new Music();
            music.setTitle(title);
            music.setSinger(singer);
            music.setUrl(url);
            music.setUserid(userId);
            int ret = service.insertService(music);
            if(ret==1){
                //map.put("msg",true);
                resp.sendRedirect("index.html");//重定向到页面
            }else {
                //数据库上传失败,同时删除服务器上已经有的文件
                System.out.println("上传失败!不能重复上传");
                part.delete();
                // map.put("msg",false);
                resp.sendRedirect("index.html");
            }
        }
    }
}

上传视频


import Service.MVService;
import entity.MV;
import entity.User;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

@WebServlet("/uploadMV")
public class UploadMVServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HashMap<String,Object> map = new HashMap<>();
        //判断文件是普通表单还是带文件的目录
           if(ServletFileUpload.isMultipartContent(request)){
               System.out.println("..");
           }
           //创建上传文件的保存路径,在WEB_INF下
        String uploadPath = this.getServletContext().getRealPath("\\MV");
        File uploadFile = new File(uploadPath);
        if(!uploadFile.exists()){
            uploadFile.mkdir();//创建目录
        }
        //缓存--临时文件
        String tmpPath = this.getServletContext().getRealPath("/tmp");
        File tmpFile = new File(tmpPath);
        if(!tmpFile.exists()){
            tmpFile.mkdir();//创建目录
        }
        //通过这个工厂设置缓冲区
        DiskFileItemFactory factory = new DiskFileItemFactory();
//        factory.setSizeThreshold(1024*1024);
//        factory.setRepository(tmpFile);
        //
        ServletFileUpload upload = new ServletFileUpload(factory);
//        //监听文件上传大小
//        upload.setProgressListener(new ProgressListener() {
//            @Override
//            public void update(long l, long l1, int i) {
//                System.out.println("总大小为"+l1 +"已上传"+l);
//            }
//        });
//        upload.setHeaderEncoding("utf-8");
//        upload.setFileSizeMax(1024*1024*10);//10m
//        upload.setSizeMax(1024*1024*10);
//        //处理上传文件
        InputStream inputStream =null;
        FileOutputStream fos = null;
        String url = null;
        String ActName = null;
        String value = "";
        try {
            //请求前端解析 封装为一个fileItem对象  从ServletFileUpload对象获得
            List<FileItem> fileItemList = upload.parseRequest(request);
            for (FileItem fileItem:fileItemList) {

                if (fileItem.isFormField()) {
                    String name = fileItem.getFieldName();
                    if ("actor".equals(name)) {
                        value = fileItem.getString("UTF-8");
                    }
                    System.out.println(value + "oooooo");

                } else {//文件情况下
                    String name = fileItem.getName();
                    System.out.println("上传的文件名为:" + name);
                    if (name.trim().equals("") || name == null) {
                        continue;
                    }
                    String filename = name.substring(name.lastIndexOf("/") + 1);

                    String[] Name = name.split("\\.");
                    ActName = Name[0];
                    url = "MV/" + ActName;
                    System.out.println(url);
                    //获取文件后缀
                    String fileExtName = name.substring(name.lastIndexOf(".") + 1);
                    System.out.println(filename + "...." + fileExtName);
                    //可以使用UUID 保证
                    //  String uuidPath = UUID.randomUUID().toString();
                    //存放地址
                    //   String realPath = uploadPath+"/"+uuidPath;
                    //  File realPathFile = new File(realPath);
                    // if(!realPathFile.exists()){
                    //      realPathFile.mkdir();
                    //   }
                    //文件传输
                    inputStream = fileItem.getInputStream();
                    fos = new FileOutputStream(uploadPath + "\\" + filename);
                    System.out.println(filename + "***");
                    //创建缓冲区
                    byte[] buffer = new byte[1024 * 1024];
                    int len = 0;
                    while ((len = inputStream.read(buffer)) > 0) {
                        fos.write(buffer, 0, len);
                    }
                }
            }
                    MVService service = new MVService();
                    MV mv = new MV();
                    mv.setName(ActName);
                    mv.setActor(value);//怎么获取提交的表单中的actor
                    mv.setUrl(url);
                    User user = (User) request.getSession().getAttribute("user");
                    mv.setUserid(user.getId());
                    int insert = service.insert(mv);
                    if(insert==1){
                        response.sendRedirect("MV.html");//重定向到页面
                    }else {
                        System.out.println("上传失败!请重新上传");

                        // map.put("msg",false);
                        response.sendRedirect("index.html");
                    }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }finally {
            //关闭流
            if(fos!=null){
                fos.close();
            }
           if(inputStream!=null){
               inputStream.close();
           }
           }
    }
}


总结

贴一些通用的代码,可以作为记录,在这个项目中收获很多,前端使用ajax异步发送请求,前后端用json传递数据,达到交互的目的,要注意的问题有很多,注意抓包工具的使用以及页面上前端代码可以用F12开发者工具来查看调式,注意路径、各个名称的对应关系,包括大小写,数据库的属性对应,数据库中表多了很容易混乱,等等情况,做一个项目要调试很多很多次,我感觉不仅磨练意志,还磨练我的斗志,如果实在找不到问题最好积极求助哟

  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 打赏
    打赏
  • 扫一扫,分享海报

参与评论 您还未登录,请先 登录 后发表或查看评论
©️2022 CSDN 皮肤主题:数字20 设计师:CSDN官方博客 返回首页

打赏作者

2_int

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值