Skip to content

Instantly share code, notes, and snippets.

@relax-more
Created February 20, 2013 08:19
Show Gist options
  • Save relax-more/4993876 to your computer and use it in GitHub Desktop.
Save relax-more/4993876 to your computer and use it in GitHub Desktop.
[java] [spring] Spring@ResponseBodyを利用して、HeaderとjsonStringを返す  Access-Control-Allow-OriginをresponceHeaderに設定するために利用
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.google.gson.JsonObject;
public class UploadController{
@RequestMapping(value = "/upload")
@ResponseBody
public ResponseEntity<String> upload(@RequestParam("uploader") MultipartFile multipartFile)
throws IllegalStateException, IOException {
LOGGER.info("upload in multipart.");
String filePath = "filepath/as/you/like"
String fileName = multipartFile.getName();
File file;
// start logic
if (!thread.isAlive()) {
thread = new Thread(runner);
thread.start();
}
try {
file = new File(filePath, fileName);
multipartFile.transferTo(file);
LOGGER.info("execute transfer");
} catch (Exception e) {
e.printStacktrace();
// TODO hundling
}
return createACAOAllResponce(ResultCode.SUCCESS, "upload successfully completed.");
}
private ResponseEntity<String> createACAOAllResponce(ResultCode resultCode, String message){
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("status", resultCode.getStatus());
jsonObject.addProperty("msg", message);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_JSON);
responseHeaders.set("Access-Control-Allow-Origin", "*");
return new ResponseEntity<String>(jsonObject.toString(), responseHeaders, HttpStatus.OK);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment