Last active
May 8, 2016 03:32
-
-
Save ringoluo/4c162d03a9530b85745ae9b365b5b6ae to your computer and use it in GitHub Desktop.
Upload File with JSON
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
<input type="file" onchange="previewFile()"> | |
<button onclick="upload()">Upload</button> | |
<a>Download</a> | |
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script> | |
<script> | |
var aFile = {}; | |
function previewFile() { | |
var file = document.querySelector('input[type=file]').files[0]; | |
console.log(file.name); | |
aFile.name = file.name; | |
var reader = new FileReader(); | |
reader.addEventListener("load", function () { | |
console.log(reader.result); | |
aFile.content = reader.result; | |
$('a').attr('download', file.name); | |
$('a').attr('href', reader.result); | |
}, false); | |
if (file) { | |
reader.readAsDataURL(file); | |
} | |
} | |
function upload() { | |
$.ajax({ | |
type: "POST", | |
url: "upload", | |
data: JSON.stringify(aFile), | |
dataType: "json", | |
contentType: "application/json;charset=utf-8" | |
}); | |
} | |
</script> |
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
@Controller | |
public class FileController { | |
@RequestMapping(value = "upload", method = RequestMethod.POST) | |
@ResponseBody | |
public String uploadFile(@RequestBody Map<String, String> file) throws IOException { | |
System.out.println(file.get("name")); | |
System.out.println(file.get("content")); | |
byte[] fileContent = Base64.decodeBase64(file.get("content").split(",")[1]); | |
Files.write(fileContent, new File("/Users/ringoluo/Desktop/" + file.get("name"))); | |
return "ok"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment