Created
May 31, 2015 06:12
-
-
Save tveimo/b778b5ae59c614329d66 to your computer and use it in GitHub Desktop.
Example Spring MVC controller to accept file uploaded with https://gist.github.com/iampivot/6922245b057a7930e2d8
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 example.controller; | |
import java.io.IOException; | |
import java.util.List; | |
import org.apache.log4j.Logger; | |
import org.json.JSONArray; | |
import org.json.JSONObject; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.http.HttpStatus; | |
import org.springframework.http.ResponseEntity; | |
import org.springframework.stereotype.Controller; | |
import org.springframework.util.FileCopyUtils; | |
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; | |
@Controller | |
public class FileUploadController { | |
protected static final Logger log = Logger.getLogger(FileUploadController.class); | |
// Optionally add your @ModelAttribute to accept the rest of the form data, eg. | |
// | |
// public String insert(@RequestParam("files") MultipartFile [] images, @Valid @ModelAttribute("company") Company company, | |
// BindingResult result, ModelMap model) { | |
@RequestMapping(value = "/media/upload", method = RequestMethod.POST) | |
public ResponseEntity<String> upload(@RequestParam("files") List<MultipartFile> images) { | |
log.debug("uploading media"); | |
JSONObject jsonMaster = new JSONObject (); | |
JSONArray jsonArray = new JSONArray(); | |
for (MultipartFile mpf: images) { | |
log.debug(mpf.getOriginalFilename() + " uploaded"); | |
JSONObject jo = new JSONObject(); | |
jo.put("name", mpf.getOriginalFilename()); | |
jo.put("size", mpf.getSize()); | |
jo.put("type", mpf.getContentType()); | |
try { | |
// create temporary file somewhere, get OutputStream | |
// FileCopyUtils.copy(mpf.getBytes(), os); | |
} catch (IOException e) { | |
log.error("error while uploading file; ", e); | |
} | |
jsonArray.put(jo); | |
} | |
jsonMaster.put("files", jsonArray); | |
return new ResponseEntity<>(jsonMaster.toString(), HttpStatus.CREATED); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment