1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; public class FileUtil {
public String upload(MultipartFile file) throws IOException { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); String newFileName = sdf.format(new Date()) + file.getOriginalFilename(); String filePath = "E:\\file"; File targetFile = new File(filePath); if (!targetFile.exists()) { targetFile.mkdirs(); } String lastFilePath = filePath + "/" + newFileName; FileOutputStream out = null; String fileUrl = null; try { out = new FileOutputStream(lastFilePath); out.write(file.getBytes()); fileUrl = "http://127.0.0.1:9000" + File.separator + newFileName; } catch (Exception e) { e.printStackTrace(); } finally { if (out != null) { try { out.flush(); } catch (IOException e) { e.printStackTrace(); } try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } return fileUrl; } }
|