Last active
November 12, 2015 00:33
-
-
Save sentimens/b0c2161bc4a6b8c068d1 to your computer and use it in GitHub Desktop.
파일업로드 랜덤이름 생성소스
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.test.web; | |
import java.io.File; | |
import java.io.IOException; | |
import org.apache.commons.io.FileUtils; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.stereotype.Service; | |
import org.springframework.web.multipart.MultipartFile; | |
import com.test.model.Board; | |
import com.test.model.FileInfo; | |
@Service | |
public class BoardServiceImpl implements BoardService{ | |
// 경로의 표시를 위해 역슬러시 2개를 적었다. | |
private final String PATH = "C:\\upload\\"; | |
@Autowired | |
private BoardDao boardDao; | |
@Autowired | |
private FileInfo fileInfo; | |
@Override | |
public int addBoard(Board board,String id) { | |
MultipartFile[] f = board.getMultipartFile(); | |
for(MultipartFile mf : f){ | |
// 오늘날짜 천분의 일초 구하여 | |
// file 이름은 시간+랜덤 숫자 는 중복될 일이 거의 없다. 기존 파일중 중복된 이름을 찾는것은 검색연산작업을 수행하기 때문에 좋은방법이 아니다. | |
// 디비에 저장하고 view안에 표시 및 | |
// 폴인키 조인 | |
// 폴인키 아니면 서브쿼리 | |
try{ | |
long t = System.currentTimeMillis(); | |
int r = (int)(Math.random()*1000000); | |
String fileId =""+t+r; | |
String realName = mf.getOriginalFilename(); | |
File temp = new File(PATH+fileId); | |
// 디비에 저장되는 DTO 멤버변수에 값지정 | |
fileInfo.setFileId(fileId); | |
fileInfo.setFileName(realName); | |
fileInfo.setUserId(id); | |
// 만약에 복사할 파일이 읽기전용이면 예외를 만들거나 저장할 공간에 용량이 없으면 예외가 발생 | |
FileUtils.writeByteArrayToFile(temp, mf.getBytes()); | |
boardDao.fileUpload(fileInfo); | |
System.out.println("파일 업로드 성공"); | |
} catch (IOException e){ | |
System.out.println("파일 업로드 실패"); | |
e.printStackTrace(); | |
} | |
} | |
return 0; | |
} | |
@Override | |
public int selectAll() { | |
fileInfo = boardDao.SelectOne(); | |
System.out.println(fileInfo.getFileId()); | |
System.out.println(fileInfo.getFileName()); | |
System.out.println(fileInfo.getUserId()); | |
// 파일가져오기 | |
File temp = FileUtils.getFile(PATH, fileInfo.getFileId()); | |
System.out.println(temp.getName()); | |
return 0; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment