I have a problem with uploading image from android application to spring server. First of all i have this method on my server:
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public String fileUpload(#RequestBody MultipartFile file) {
System.out.println("post image");
try {
// Get the file and save it somewhere
byte[] bytes = file.getBytes();
System.out.println(bytes.length);
//save file in server - you may need an another scenario
Path path = Paths.get("file:///E:/together/images/" + file.getOriginalFilename());
Files.write(path, bytes);
} catch (IOException e) {
e.printStackTrace();
}
//redirect to an another url end point
return "redirect";
}
And in my android app i'am get uri of image from image gallery and try call post method
FileEntity fileEntity = new FileEntity(new File(getRealPathFromURI(uri)), "application/octet-stream");
new Requests.Async().execute(fileEntity);
ublic static class Async extends AsyncTask<FileEntity,Void,Void>{
#Override
protected void onPreExecute() {
restTemplate = RestTemplateSingleton.newInstance().getRestTemplate();
}
#Override
protected Void doInBackground(FileEntity... uris) {
try{
restTemplate.postForObject(Requests.insertImage(),uris[0],FileEntity.class);
}catch (HttpClientErrorException | HttpServerErrorException httpClientOrServerExc) {
return null;
}
return null;
}
}
but i get 500 http status when call this method. what's my mistake?
Related
I have to write code using java and GeoTools to do a WMS request, get the image and save it to a specific location on my computer. I've followed the GeoTools WMS tutorial and the code compiles without errors, but I don't know how to check if it had worked or how to save the requested image?
Here is the GetMap request with all the necessary parameters: http://ows.mundialis.de/services/service?request=GetMap&service=WMS&version=1.3.0&layers=OSM-Overlay-WMS&styles=default&crs=EPSG%3A4326&bbox=47.75,12.98,47.86,13.12&&width=2000&height=2000&format=image/png&transparent=true
Here is the code:
public class WmsConnectorMaven {
public static void main(String[] args) {
URL url = null;
try {
url = new URL("http://ows.mundialis.de/services/service?service=wms&version=1.3.0&request=GetCapabilities");
} catch (MalformedURLException e) {
//will not happen
}
WebMapServer wms = null;
try {
wms = new WebMapServer(url);
GetMapRequest request = wms.createGetMapRequest();
request.addLayer("OSM-Overlay-WMS", "defualt");
request.setFormat("image/png");
request.setDimensions("800", "800"); //sets the dimensions of the image to be returned from the server
request.setTransparent(true);
request.setSRS("EPSG:4326");
request.setBBox("47.75,12.98,47.86,13.12");
GetMapResponse response = (GetMapResponse) wms.issueRequest(request);
BufferedImage image = ImageIO.read(response.getInputStream());
/* File outputfile = new File("saved.png");
ImageIO.write(image, "png", outputfile); */
// FileOutputStream img = new FileOutputStream("C:\\Users\\Edhem\\Desktop\\WMSimage.png");
} catch (IOException e) {
//There was an error communicating with the server
//For example, the server is down
} catch (ServiceException e) {
//The server returned a ServiceException (unusual in this case)
}
}
}
You need to check the contentType of the returned response and make a decision based on that value. Something like:
try {
GetMapResponse response = wms.issueRequest(getMapRequest);
if (response.getContentType().equalsIgnoreCase(format)) {
BufferedImage image = ImageIO.read(response.getInputStream());
return image;
} else {
StringWriter writer = new StringWriter();
IOUtils.copy(response.getInputStream(), writer);
String error = writer.toString();
System.out.println(error);
return null;
}
} catch (ServiceException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
UPDATE
I just ran your code with my checks and I get:
<?xml version="1.0"?>
<ServiceExceptionReport version="1.3.0"
xmlns="http://www.opengis.net/ogc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.opengis.net/ogc
http://schemas.opengis.net/wms/1.3.0/exceptions_1_3_0.xsd">
<ServiceException code="StyleNotDefined">unsupported styles: defualt</ServiceException>
</ServiceExceptionReport>
removing the (misspelt) "defualt" gives (which I guess is right):
I'm using the following REST method to be called from the UI to download the ZIP archive:
#RequstMapping("/download")
public void downloadFiles(HttpServletResponse response) {
response.setStatus(HttpServletResponse.SC_OK);
try {
downloadZip(response.getOutputStream());
} catch (IOException e) {
throw new RuntimeException("Unable to download file");
}
}
private void downloadZip(OutputStream output) {
try (ZipOutputStream zos = new ZipOutputStream(outputStream)) {
byte[] bytes = getBytes();
zos.write(bytes);
zos.closeEntry();
} catch (Exception e) {
throw new RuntimeException("Error on zip creation");
}
}
It's working fine, but I wanted to make the code more Spring oriented, e.g. to return ResponceEntity<Resource> instead of using ServletOutputStream of Servlet API.
The problem is that I couldn't find a way to create Spring resource from the ZipOutputStream.
Here is a way to return bytestream, you can use it to return zip file as well by setting content-type.
#RequestMapping(value = "/download", method = RequestMethod.GET)
#ResponseBody
public ResponseEntity<Resource> download() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
InputStream is = null; // get your input stream here
Resource resource = new InputStreamResource(is);
return new ResponseEntity<>(resource, headers, HttpStatus.OK);
}
I have a web site and I want to be able to download file in mobile devices.
I donĀ“t have problem when I access to my web page and download an image from pc's browser but if I want to do from mobile device the image doesn't download, mobile's browser opens other page with image.
This is my code for this section:
#Override
public void download(String nameImage, HttpServletResponse response) {
ImageEntity image = imageRepository.findByName(nameImage);
response.setContentType("image/" + image.getExtension());
File localFile = new File(pathManager.getPathCompleteOfImageUpload()+nameImage);
try {
InputStream is = new FileInputStream(localFile);
org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
response.flushBuffer();
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
and Header is
private void setHeader(HttpServletResponse response, String name) {
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", name);
response.setHeader(headerKey, headerValue);
}
Can you help me?
Thanks you so much!
I am using Jersey to serve a bunch of media-type files from resource folder inside a Jar file. I have the file URL returned by getClassLoader().getResource() and the InputStream returned by getClassLoader().getResourceAsStream(), is there a way for Jersey to detect the content-type for this file?
#GET
#Path("/attachment")
#Consumes("text/plain; charset=UTF-8")
#Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getAttachment(
#QueryParam("file") String fileName) {
try {
if (fileName == null) {
System.err.println("No such item");
return Response.status(Response.Status.BAD_REQUEST).build();
}
StreamingOutput stream = new StreamingOutput() {
#Override
public void write(OutputStream output) throws IOException {
try {
// TODO: write file content to output;
} catch (Exception e) {
e.printStackTrace();
}
}
};
return Response.ok(stream, "image/png") //TODO: set content-type of your file
.header("content-disposition", "attachment; filename = "+ fileName)
.build();
}
}
System.err.println("No such attachment");
return Response.status(Response.Status.BAD_REQUEST).build();
} catch (Exception e) {
System.err.println(e.getMessage());
return Response.status(Response.Status.BAD_REQUEST).build();
}
}
At the second TODO you can use (if Java 7):
Path source = Paths.get("/images/something.png");
Files.probeContentType(source);
to retrieve the mimeType.
I didn't find a solution using Jersey. But I found Apache Tika works perfectly in this case, simply do
Tika tika = new Tika();
String contentType = tika.detect(path);
where path is the abstract file path, like "index.html, ui.js, test.css"
I wrote this AsyncTask class that sends an array of POST data to my php server with no problem. Now I want to extend it so that it also sends a file to same script (I have already the receive handling in the php file). What I mean is I want it to post DATA + FILE in one go. Something like multipart entity or something from HTML action to php script.
What would I need to add to this class so it can upload a file with other things?
public class UpdateSnakeGameStatusTask extends AsyncTask<String, Integer, HttpResponse> {
private Context mContext;
private ArrayList<NameValuePair> mPairs;
/**
* #param context The context that uses this AsyncTask thread
* #param postPairs <b>NameValuePair</b> which contains name and post data
*/
public UpdateSnakeGameStatusTask(Context context, ArrayList<NameValuePair> postPairs) {
mContext = context;
mPairs = new ArrayList<NameValuePair>(postPairs);
}
#Override
protected HttpResponse doInBackground(String... params) {
HttpResponse response = null;
HttpPost httppost = new HttpPost(params[0]); //this is the URL
try {
httppost.setEntity(new UrlEncodedFormEntity(mPairs));
HttpClient client = new DefaultHttpClient();
response = client.execute(httppost);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
}
Ok as #greenapps suggested (credit goes to him) I solved like this.
Well not entirly solved, because I have to decode the file content at server side and save it manually on server.
so I jsut added the file content to the BasicNameValuePair that I already had:
String fileAsBase64 = Base64.encodeToString( convertToByteArray(mFile)
, Base64.DEFAULT);
mPostPairs.add(new BasicNameValuePair("filecontent", fileAsBase64));
And this is the method that converts it to byte array:
/**
* Reads a file and returns its content as byte array
* #param file file that should be returned as byte array
* #return byte[] array of bytes of the file
*/
public static byte[] convertTextFileToByteArray(File file) {
FileInputStream fileInputStream = null;
byte[] bFile = new byte[(int) file.length()];
try {
fileInputStream = new FileInputStream(file);
fileInputStream.read(bFile);
fileInputStream.close();
}catch(Exception e){
e.printStackTrace();
} finally {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}finally {
fileInputStream = null;
}
}
return bFile;
}
At the server side I do this:
$content = imap_base64 ($_POST["filecontent"]);
that takes care of decoding the content back to normal.
Hope this helps someone else too