SSM文件的上传、查询、删除案例

文件上传的几个注意点:

  1. 方法请求必须为post请求。
  2. form标签的encType属性值必须为multipart/form-data。
  3. form表单中input标签type为file。
  4. 需要导入两个jar包。
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
  1. springmvc.xml中配置
    <!--配置文件上传-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="1048576"></property>
        <!-- 设置默认编码-->
        <property name="defaultEncoding" value="utf-8"></property>
    </bean>

数据库表

实体类

public class LabFile {

    private Integer file_id;
    private String file_name;
    private String file_type;
    private String upload_time;
    private String file_url;

    ......
}

LabFileDao

public interface LabFileDao {

    /**
     * 添加文件
     * @param fileInfo
     */
    public void addFileInfo(LabFile fileInfo) throws SQLException;
    /**
     * 查询所有的文件
     * @return
     */
    public List<LabFile> findFiles() throws SQLException;
    /**
     * 根据id查询文件
     * @param fileId
     * @return
     */
    public int findFileById(Integer fileId) throws SQLException;

    /**
     * 根据id删除文件
     * @param file_id
     * @return
     */
    @Delete("delete from lab_file where file_id = #{file_id}")
    int deleteById(Integer file_id) throws SQLException;

}

FileDao.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lynu.dao.LabFileDao">

    <!--上传文件-->
    <insert id="addFileInfo" parameterType="LabFile">
        insert into lab_file (file_name,file_type,upload_time,file_url)
        values (#{file_name},#{file_type},#{upload_time},#{file_url});
    </insert>
    <!--查询所有文件-->
    <select id="findFiles" resultType="LabFile">
        select file_id,file_name,file_type,upload_time,file_url from lab_file;
    </select>

</mapper>

工具类

FileUtil

public class FileUtil {

    public FileUtil() {
    }
    public static String createFileTimestamp() {
        Date date = new Date();
        long time = date.getTime();
        return String.valueOf(time);
    }
    public static void writeFileToUrl(MultipartFile file, String fileUrl) throws IOException {
        FileOutputStream fos = new FileOutputStream(new File(fileUrl));
        fos.write(file.getBytes());
        fos.flush();
        fos.close();
    }
    public static void main(String[] args) {
        System.out.println(createFileTimestamp());
    }

}

DateUtils

public class DateUtils {

    public static String dateToStrDateTime(Date date,String dateFormat){
        SimpleDateFormat df = new SimpleDateFormat(dateFormat);
        String dateTime = df.format(date);
        return dateTime;
    }

}

LabFileService

public interface LabFileService {

    /**
     * 添加文件
     * @param fileInfo
     */
    public void addFileInfo(LabFile fileInfo) throws SQLException;
    /**
     * 查询所有的文件
     * @return
     */
    public List<LabFile> findFiles() throws SQLException;
    /**
     * 根据id查询文件
     * @param fileId
     * @return
     */
    public int findFileById(Integer fileId) throws SQLException;

    /**
     * 根据id删除文件
     * @param file_id
     * @return
     */
    @Delete("delete from lab_file where id = #{file_id}")
    int deleteById(Integer file_id) throws SQLException;

}

LabFileServiceImpl

@Service("fileService")
public class LabFileServiceImpl implements LabFileService {

    @Autowired
    private LabFileDao labFileDao;

    @Override
    public void addFileInfo(LabFile fileInfo) throws SQLException {
        labFileDao.addFileInfo(fileInfo);
    }

    @Override
    public List<LabFile> findFiles() throws SQLException {
        return labFileDao.findFiles();
    }

    @Override
    public int findFileById(Integer fileId) throws SQLException {
        return labFileDao.deleteById(fileId);
    }

    @Override
    public int deleteById(Integer file_id) throws SQLException {
        return labFileDao.deleteById(file_id);
    }
}

LabFileController

@Controller
@RequestMapping("/file")
public class LabFileController {

    @Autowired
    private LabFileService labFileService;


    @RequestMapping(value = {"/uploadFile"}, method = {RequestMethod.POST},produces = "application/json;charset=utf-8")
    @ResponseBody
    public LabFile upload(LabFile fileInfo,MultipartFile uploadFile, HttpServletRequest request) throws IOException {
       
        //获得文件
        byte[] buf = uploadFile.getBytes();        
        //文件名    a.txt
        String originalFileName = uploadFile.getOriginalFilename();
        //时间戳
        String time = FileUtil.createFileTimestamp();
        //文件url		/upload/1231231231231a.txt
        String fileUrl = "/upload/" + time + originalFileName;
        fileUrl = request.getServletContext().getRealPath(fileUrl);
        //向url地址存储文件
        FileUtil.writeFileToUrl(uploadFile, fileUrl);

        //向数据库中保存文件信息
        fileInfo.setFile_name(originalFileName);
        fileInfo.setFile_url(fileUrl);
        Date date = new Date();
        String dateTime = DateUtils.dateToStrDateTime(date, "yyyy-MM-dd HH:mm:ss");
        fileInfo.setUpload_time(dateTime);
      
        try {
            labFileService.addFileInfo(fileInfo);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return fileInfo;
    }

    @RequestMapping(value = "/findFiles",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String files() {
        ObjectMapper objectMapper = new ObjectMapper();
        String str = null;
        try {
            List<LabFile> files = labFileService.findFiles();
            str = objectMapper.writeValueAsString(files);
        } catch (JsonProcessingException | SQLException var5) {
            var5.printStackTrace();
        }
        return str;
    }

    @RequestMapping(value = "/delete",produces = "application/json;charset=utf-8")
    @ResponseBody
    public int delete(Integer file_id) throws SQLException {
        return labFileService.deleteById(file_id);
    }
}
原文地址:https://www.cnblogs.com/ITHSZ/p/14148837.html