Skip to content

Instantly share code, notes, and snippets.

@xx7y7xx
Last active Jun 15, 2017
Embed
What would you like to do?
Send POST request open save as dialog to save file locally
var oReq = new XMLHttpRequest();
oReq.open("POST", "/download2", true);
oReq.responseType = "arraybuffer";
oReq.onload = function(oEvent) {
var blob = new Blob([oReq.response], {type: "image/jpeg"});
saveAs(blob, "test.jpg"); // https://github.com/eligrey/FileSaver.js/
};
oReq.send();
/**
* Copy from https://github.com/hellokoding/uploadingfiles-springboot
*/
package com.hellokoding.uploadingfiles;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
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.multipart.MultipartFile;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import javax.servlet.http.HttpServletResponse;
@Controller
public class UploadingController {
public static final String uploadingdir = System.getProperty("user.dir") + "/uploadingdir/";
@RequestMapping("/")
public String uploading(Model model) {
File file = new File(uploadingdir);
model.addAttribute("files", file.listFiles());
return "uploading";
}
@RequestMapping(value = "/", method = RequestMethod.POST)
public String uploadingPost(@RequestParam("uploadingFiles") MultipartFile[] uploadingFiles) throws IOException {
for(MultipartFile uploadedFile : uploadingFiles) {
File file = new File(uploadingdir + uploadedFile.getOriginalFilename());
uploadedFile.transferTo(file);
}
return "redirect:/";
}
@RequestMapping(value = "/download", method = RequestMethod.POST)
public File downloadPost() throws IOException {
File file = new File(uploadingdir + "test.jpg");
return file;
}
@RequestMapping(value = "/download2", method = RequestMethod.POST)
public void getFile(
HttpServletResponse response) {
try {
// get your file as InputStream
InputStream is = new FileInputStream(uploadingdir + "test.jpg");
// copy it to response's OutputStream
IOUtils.copy(is, response.getOutputStream());
response.setContentType("image/jpeg");
response.setHeader("Content-Disposition", "attachment; filename=\"somefile.jpg\"");
// response.flushBuffer();
} catch (IOException ex) {
// log.info("Error writing file to output stream. Filename was '{}'", fileName, ex);
throw new RuntimeException("IOError writing file to output stream");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment