반응형
파일 업로드 폼 생성하기
txt 파일만 업로드 가능하도록 하기
txt 파일을 업로드하면 DB에 데이터가 저장되어야 함.
ServletController.java
package servlet.controller;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import servlet.service.FileService;
import servlet.service.ServletService;
@Controller
public class ServletController {
@Resource(name = "ServletService")
private ServletService servletService;
@Resource(name="FileService")
private FileService fileService;
@RequestMapping(value = "/main.do")
public String mainTest(ModelMap model) throws Exception {
System.out.println("main start");
List<Map<String, Object>> sdList = servletService.selectSD();
List<Map<String, Object>> sggList = servletService.selectSGG();
List<Map<String, Object>> bjdList = servletService.selectBJD();
model.addAttribute("sdList", sdList);
model.addAttribute("sggList", sggList);
model.addAttribute("bjdList", bjdList);
return "main/main";
}
@RequestMapping(value = "/t-file.do", method = RequestMethod.GET)
public String t_file() {
return "main/t_file";
}
@ResponseBody
@RequestMapping(value = "/t-file2.do", method = RequestMethod.POST, produces = "applecation/json;charset=UTF-8")
public String t_file(@RequestParam("file") MultipartFile upFile) throws IOException {
List<Map<String, Object>> list = new ArrayList<>();
InputStreamReader isr = new InputStreamReader(upFile.getInputStream());
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
Map<String, Object> m = new HashMap<>();
String[] lineArr = line.split("\\|");
m.put("date", lineArr[0]); // 사용_년월 date
m.put("addr", lineArr[1]); // 대지_위치 addr
.
.
.
.
list.add(m);
}
System.out.println("종료 : " + list);
fileService.uploadFile(list);
br.close();
isr.close();
return "1";
}
}
FileService.java
package servlet.service;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Service;
@Service
public interface FileService {
void uploadFile(List<Map<String, Object>> list);
}
FileServiceImpl.java
package servlet.impl;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import egovframework.rte.fdl.cmmn.EgovAbstractServiceImpl;
import servlet.service.FileService;
@Service("FileService")
public class FileServiceImpl extends EgovAbstractServiceImpl implements FileService{
@Resource(name="ServletDAO")
private ServletDAO dao;
@Override
public void uploadFile(List<Map<String, Object>> list) {
for (Map<String, Object> map : list) {
dao.selectList("servlet.uploadFile",map);
}
}
}
context-datasource.xml
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 파일 업로드 제한 크기 설정 -->
<property name="maxUploadSize" value="52428800" /> <!-- 50MB -->
</bean>
servlet-SQL.xml
<insert id="uploadFile" parameterType="Map">
INSERT INTO "테이블명"
VALUES (#{date}, #{addr}, #{newaddr}, #{sgg_cd}, #{......}, #{......},#{......})
</insert>
pom.xml
<!-- 파일업로드 -->
<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>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
<scope>provided</scope>
</dependency>
SQL Shell
명령어 : \d "테이블명"
테이블
필드명 | 종류 | Collation | NULL허용 | 초기값
-----------------+------------------------+-----------+----------+--------
date | character varying(6) | | |
addr | character varying(500) | | |
newaddr | character varying(400) | | |
newaddr_undercd | character varying(1) | | |
newaddr_mainno | numeric(5,0) | | |
newaddr_subno | numeric(5,0) | | |
used_khw | numeric(22,0) | | |
postgreSQL 튜플(행) 삭제하기
null값으로 삽입된 2개의 행을 삭제해야한다. 1, 2를 식별할 수 있는 튜플명이 없어서 어떻게 삭제해야하나? 했는데.
데이터가 null값인 것들을 삭제하는 쿼리문으로 해결.
DELETE FROM "테이블명"
WHERE
date IS NULL AND
addr IS NULL AND
ji IS NULL AND
newaddr_cd IS NULL AND
used_khw IS NULL;
main.jsp
파일 업로드 폼 및 function
<!-- 파일 업로드 폼 -->
<form id="form" style="margin-top:300px;">
<input type="file" id="file" name="file" accept="txt">
</form>
<button type="submit" id="fileBtn">업로드</button>
$(document).ready(function() {
$("#fileBtn").on("click", function() {
let fileName = $('#file').val();
if(fileName == ""){
alert("파일을 선택해주세요.");
return false;
}
let dotName = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
if(dotName == 'txt'){
$.ajax({
url : './t-file2.do',
type : 'POST',
dataType: 'json',
data : new FormData($('#form')[0]),
cache : false,
contentType : false,
processData : false,
enctype: 'multipart/form-data',
success : function(result) {
alert(result);
},
error : function(Data) {
}
});
}else{
alert("확장자가 안 맞으면 멈추기");
}
});
});
main.jsp 전체코드
<style type="text/css">
.map {
height: 800px;
width: 60%;
float: right; /* 맵을 우측에 배치합니다. */
}
/* .select-box-container {
display: flex;
justify-content: left;
align-items: left;
height: 50vh;
} */
.select-box {
margin: 0 20px;
}
.select-box-container {
position: fixed;
top: 0;
left: 0;
width: 100%;
background-color: white;
padding: 10px;
display: flex;
z-index: 1000; /* 옵션 선택 부분을 다른 요소들보다 위로 올립니다. */
}
</style>
</head>
<body>
<div class="map-container">
<div id="map" class="map"></div>
</div>
<div class="select-box-container">
<div class="select-box">
<h2>시도 선택</h2>
<select id="sdSelect">
<option value="">선택</option>
<c:forEach var="row" items="${sdList}">
<option value="${row.sd_nm}">${row.sd_nm}</option>
</c:forEach>
</select>
</div>
<div class="select-box">
<h2>시군구 선택</h2>
<select id="sggSelect">
<option value="">선택</option>
<c:forEach var="row" items="${sggList}">
<option value="${row.sgg_nm}">${row.sgg_nm}</option>
</c:forEach>
</select>
</div>
<div class="select-box">
<h2>법정동 선택</h2>
<select id="bjdSelect">
<option value="">선택</option>
<c:forEach var="row" items="${bjdList}">
<option value="${row.bjd_nm}">${row.bjd_nm}</option>
</c:forEach>
</select>
</div>
</div>
<hr>
<!-- 파일 업로드 폼 -->
<form id="form" style="margin-top:300px;">
<input type="file" id="file" name="file" accept="txt">
</form>
<button type="submit" id="fileBtn">업로드</button>
<!------------------------------------------------------------------------------------------------>
<!------------------------------------------------------------------------------------------------>
<script type="text/javascript">
$(document).ready(function() {
let map = new ol.Map(
{ // OpenLayer의 맵 객체를 생성한다.
target : 'map', // 맵 객체를 연결하기 위한 target으로 <div>의 id값을 지정해준다.
layers : [ // 지도에서 사용 할 레이어의 목록을 정희하는 공간이다.
new ol.layer.Tile(
{
source : new ol.source.OSM(
{url : 'https://api.vworld.kr/req/wmts/1.0.0/---------/Base/{z}/{y}/{x}.png' // vworld의 지도를 가져온다.
})
}) ],
view : new ol.View({ // 지도가 보여 줄 중심좌표, 축소, 확대 등을 설정한다. 보통은 줌, 중심좌표를 설정하는 경우가 많다.
center : ol.proj.fromLonLat([ 128.4,
35.7 ]),
zoom : 7
})
});
// 시도 선택 시 시군구 옵션 업데이트
$('#sdSelect').on("change", function() {
var sdValue = $(this).val();
$.ajax({
type: 'post',
url: '/getSggList.do',
data: { 'sdValue': sdValue },
dataType : "json",
success: function(data) {
var sggSelect = $('#sggSelect');
sggSelect.empty(); // 기존 옵션 제거
sggSelect.append('<option value="">선택</option>'); // 기본 선택 옵션 추가
$.each(data, function(index, item) {
sggSelect.append('<option value="' + item.sgg_nm + '">' + item.sgg_nm + '</option>'); // 응답으로 받은 데이터로 옵션 추가
});
// 시도에 해당하는 레이어 추가
map.addLayer(new ol.layer.Tile({
source: new ol.source.TileWMS({
url: 'http://localhost/geoserver/korea/wms?service=WMS',
params: {
'VERSION': '1.1.0',
'LAYERS': 'korea:tl_sd',
'CQL_FILTER': "sd_nm LIKE '%" + sdValue + "%'",
'SRS': 'EPSG:3857',
'FORMAT': 'image/png'
},
serverType: 'geoserver'
}),
opacity: 0.5
}));
}
});
});
// 시군구 선택 시 법정동 옵션 업데이트
$('#sggSelect').on("change", function() {
var sggValue = $(this).val();
$.ajax({
type: 'post',
url: '/getBjdList.do',
data: { 'sggValue': sggValue },
dataType: "json",
success: function(response) {
var bjdSelect = $('#bjdSelect');
bjdSelect.empty(); // 기존 옵션 제거
bjdSelect.append('<option value="">선택</option>'); // 기본 선택 옵션 추가
$.each(response, function(index, item) {
bjdSelect.append('<option value="' + item.value + '">' + item.name + '</option>'); // 응답으로 받은 데이터로 옵션 추가
});
// 시군구에 해당하는 레이어 추가
map.addLayer(new ol.layer.Tile({
source: new ol.source.TileWMS({
url: 'http://localhost/geoserver/korea/wms?service=WMS',
params: {
'VERSION': '1.1.0',
'LAYERS': 'korea:tl_sgg',
'CQL_FILTER': "sgg_nm LIKE '%" + sggValue + "%'",
'SRS': 'EPSG:3857',
'FORMAT': 'image/png'
},
serverType: 'geoserver'
}),
opacity: 0.5
}));
}
});
});
//파일 업로드 버튼 클릭 이벤트 핸들러
$("#fileBtn").on("click", function() {
let fileName = $('#file').val();
if (fileName == "") {
alert("파일을 선택해주세요.");
return false;
}
let dotName = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
if (dotName == 'txt') {
$.ajax({
url: './t-file2.do',
type: 'POST',
dataType: 'json',
data: new FormData($('#form')[0]),
cache: false,
contentType: false,
processData: false,
enctype: 'multipart/form-data',
success: function(result) {
alert(result);
},
error: function(Data) {
}
});
} else {
alert("확장자가 안 맞으면 멈추기");
}
});
});
</script>
</body>
</html>
반응형
'프로젝트' 카테고리의 다른 글
[GeoServer] 시도, 시군구, 범례 레이어 겹치지 않게 (0) | 2024.04.04 |
---|---|
[GeoServer] spring과 DB연동해서 차트 그리기 (0) | 2024.04.01 |
[GeoServer] 선택한 지역에 해당되는 레이어 표시하기 (0) | 2024.03.27 |
[GeoServer] 시도, 시군구, 법정동 구역 구분하기 (0) | 2024.03.27 |
[GeoServer] 지오서버 시작하기 Openlayers, 작업 공간 추가 (0) | 2024.03.27 |
댓글