I have a android app and i wand to upload from this app, Large image (in this case 32MB) to Spring Server, but i got java.net.SocketException: sendto failed: EPIPE (Broken pipe) error.
i use this method :
public static void setPicture(User user, Picture picture, HavePicture havePicture, File file) {
try {
URL url = new URL(Request.BASE_URL + Request.BASE_PATH + Request.GAME_SYSTEM_PATH + Request.SET_PICTURE_PATH);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setUseCaches(false);
connection.setDoOutput(true); // indicates POST method
connection.setDoInput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
connection.setRequestProperty("User-Agent", "CodeJava Agent");
connection.setRequestProperty("Test", "Bonjour");
//load file with multi small pices not one lage pice good to use large filse
connection.setChunkedStreamingMode(1024);
OutputStream outputStream = connection.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, Request.CHARSET), true);
addFormField(writer, Request.PARAM_USER, Json.toJson(user));
addFormField(writer, Request.PARAM_PICTURE, Json.toJson(picture));
addFormField(writer, Request.PARAM_HAVE_PICTURE, Json.toJson(havePicture));
addFilePart(writer, outputStream, Request.PARAM_FILE, file);
StringBuffer response = new StringBuffer();
writer.append(LINE_FEED).flush();
writer.append("--" + boundary + "--").append(LINE_FEED);
writer.close();
// checks server's status code first
int status = connection.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
connection.disconnect();
} else {
throw new IOException("Server returned non-OK status: " + status);
}
String a = response.toString();
System.out.println(a);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
the params : user , picture, and havePicture are some objects that i whant to send they json with the big image, this method actully work with small image least then 1MB.
here the rest of the methods :
private static void addFormField(PrintWriter writer, String name, String value) {
writer.append("--" + boundary).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name=\"" + name + "\"").append(LINE_FEED);
writer.append("Content-Type: text/plain; charset=" + Request.CHARSET).append(LINE_FEED);
writer.append(LINE_FEED);
writer.append(value).append(LINE_FEED);
writer.flush();
}
Use for the image file :
private static void addFilePart(PrintWriter writer,OutputStream outputStream, String fieldName, File uploadFile) throws IOException {
String fileName = uploadFile.getName();
writer.append("--" + boundary).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName + "\"").append(LINE_FEED);
writer.append("Content-Type: "+URLConnection.guessContentTypeFromName(fileName)).append(LINE_FEED);
writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
FileInputStream inputStream = new FileInputStream(uploadFile);
writer.append("Content-length: "+inputStream.available()).append(LINE_FEED);
System.out.println("- - "+"Content-length: "+inputStream.available());
writer.append(LINE_FEED);
writer.flush();
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
inputStream.close();
writer.append(LINE_FEED);
writer.flush();
}
Here my completed error :
java.net.SocketException: sendto failed: EPIPE (Broken pipe) at libcore.io.IoBridge.maybeThrowAfterSendto(IoBridge.java:586) at libcore.io.IoBridge.sendto(IoBridge.java:555) at java.net.PlainSocketImpl.write(PlainSocketImpl.java:520) at java.net.PlainSocketImpl.access$100(PlainSocketImpl.java:43) at java.net.PlainSocketImpl$PlainSocketOutputStream.write(PlainSocketImpl.java:272) at com.android.okio.Okio$1.write(Okio.java:70) at com.android.okio.RealBufferedSink.emitCompleteSegments(RealBufferedSink.java:116) at com.android.okio.RealBufferedSink.write(RealBufferedSink.java:44) at com.android.okhttp.internal.http.HttpConnection$ChunkedSink.write(HttpConnection.java:334) at com.android.okio.RealBufferedSink.emitCompleteSegments(RealBufferedSink.java:116) at com.android.okio.RealBufferedSink$1.write(RealBufferedSink.java:131) at com.mayan.ameritrade.android.tools.Server$override.addFilePart(Server.java:435) at com.mayan.ameritrade.android.tools.Server$override.access$dispatch(Server.java) at com.mayan.ameritrade.android.tools.Server.addFilePart(Server.java:0) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.tools.fd.runtime.AndroidInstantRuntime.invokeProtectedStaticMethod(AndroidInstantRuntime.java:170) at com.mayan.ameritrade.android.tools.Server$override.setPicture(Server.java:363) at com.mayan.ameritrade.android.tools.Server$override.access$dispatch(Server.java) at com.mayan.ameritrade.android.tools.Server.setPicture(Server.java:0) at com.mayan.ameritrade.android.MainActivity$2$1.run(MainActivity.java:99) at java.lang.Thread.run(Thread.java:818) Caused by: android.system.ErrnoException: sendto failed: EPIPE (Broken pipe) at libcore.io.Posix.sendtoBytes(Native Method) at libcore.io.Posix.sendto(Posix.java:206) at libcore.io.BlockGuardOs.sendto(BlockGuardOs.java:278) at libcore.io.IoBridge.sendto(IoBridge.java:553) ... 20 more
I dont now what to do, thank for any help !
You cannot use PrintWriter to upload an image... well you dont... but...
PrintWriter is for texts only.
You are mixing PrintWriter and the normal OutputStream. That will not do.
You should write to one type of stream only.
My problem solved ! thank to #Randyka Yudhistira and #greenapps for help,
my problem was some unnecessary code in client, And Mainly my Spring server not able to upload large files
Solution
Add inserver side :
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSizePerFile">yourMaxSizeToUpload</property>
</bean>
or
#Bean
public CommonsMultipartResolver getCommonsMultipartResolver() {
CommonsMultipartResolver resolver = new CommonsMultipartResolver();
resolver.setMaxUploadSize(yourMaxSizeToUpload);
return resolver;
}
If this not work try to remove unnecessary code like :
writer.append("Content-length: "+inputStream.available()).append(LINE_FEED);
in my case.
Related
I want to send an audio file to a server via a POST request in my Java Android App. The following code is what I currently have, however, it is not working.
I have found this class implementing a MultiPart Utility:
public class MultipartUtility {
private static final String LINE_FEED = "\r\n";
private HttpURLConnection httpConn;
private String charset;
private OutputStream outputStream;
private PrintWriter writer;
private final String boundary;
public MultipartUtility(String requestURL, String charset)
throws IOException {
this.charset = charset;
// creates a unique boundary based on time stamp
boundary = "===" + System.currentTimeMillis() + "===";
URL url = new URL(requestURL);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true); // indicates POST method
httpConn.setDoInput(true);
httpConn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
httpConn.setRequestProperty("User-Agent", "CodeJava Agent");
httpConn.setRequestProperty("Test", "Bonjour");
outputStream = httpConn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
true);
}
public void addFormField(String name, String value) {
writer.append("--" + boundary).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name=\"" + name + "\"")
.append(LINE_FEED);
writer.append("Content-Type: text/plain; charset=" + charset).append(
LINE_FEED);
writer.append(LINE_FEED);
writer.append(value).append(LINE_FEED);
writer.flush();
}
public void addFilePart(String fieldName, File uploadFile)
throws IOException {
String fileName = uploadFile.getName();
writer.append("--" + boundary).append(LINE_FEED);
writer.append(
"Content-Disposition: form-data; name=\"" + fieldName
+ "\"; filename=\"" + fileName + "\"")
.append(LINE_FEED);
writer.append(
"Content-Type: "
+ URLConnection.guessContentTypeFromName(fileName))
.append(LINE_FEED);
writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
writer.append(LINE_FEED);
writer.flush();
FileInputStream inputStream = new FileInputStream(uploadFile);
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
inputStream.close();
writer.append(LINE_FEED);
writer.flush();
}
public void addHeaderField(String name, String value) {
writer.append(name + ": " + value).append(LINE_FEED);
writer.flush();
}
public List<String> finish() throws IOException {
List<String> response = new ArrayList<String>();
writer.append(LINE_FEED).flush();
writer.append("--" + boundary + "--").append(LINE_FEED);
writer.close();
// checks server's status code first
int status = httpConn.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
response.add(line);
}
reader.close();
httpConn.disconnect();
} else {
throw new IOException("Server returned non-OK status: " + status);
}
return response;
}
}
and want to send a POST request to a server with this client code:
String requestURL = "http://0.0.0.0:5000/test";
try {
com.eng.elfarsisy.recored.MultipartUtility multipart = new com.eng.elfarsisy.recored.MultipartUtility(requestURL, charset);
multipart.addHeaderField("User-Agent", "CodeJava");
multipart.addHeaderField("Test-Header", "Header-Value");
multipart.addFormField("description", "Cool Pictures");
multipart.addFormField("keywords", "Java,upload,Spring");
multipart.addFilePart("fileUpload", uploadFile1);
List<String> response = multipart.finish();
System.out.println("SERVER REPLIED:");
for (String line : response) {
System.out.println(line);
}
} catch (IOException ex) {
System.err.println(ex);
}
However I am getting this response:
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
W/System.err: java.net.SocketException: Permission denied
How can I fix this? Any ideas would be greatly appreciated.
Have you added this permission to your manifest?
<uses-permission android:name="android.permission.INTERNET"/>
I am trying to create http client for simple service testing. In server side code parameters are getting read by parsing request as mentioned below. I want to set some parameters so that fields will have those parameters
final FileItemFactory factory = new DiskFileItemFactory();
final ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> fields = upload.parseRequest(request);
But I am not able to set parameters those from http client so that value of fields is always empty. I am trying following code
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
httpPost.setHeader("Connection", "keep-alive");
httpPost.setHeader("Content-Type",
"multipart/form-data; boundary=----WebKitFormBoundaryv1eAhALrGwBQXRIp");
httpPost.setHeader("Host", "localhost:8080");
httpPost.setHeader(
"User-Agent",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.101 Safari/537.36");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("test", "red"));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
CloseableHttpResponse response = httpClient.execute(httpPost);
} catch (Exception e) {
}
Please suggest if I am doing something wrong.
Here addFormField() method would do the trick for you. Using addFormField(), the parameter set will be received in your field variable.
public class MultipartUtility {
private final String boundary;
private static final String LINE_FEED = "\r\n";
private HttpURLConnection httpConn;
private String charset;
private OutputStream outputStream;
private PrintWriter writer;
public MultipartUtility(String requestURL, String charset)
throws IOException {
this.charset = charset;
// creates a unique boundary based on time stamp
boundary = "===" + System.currentTimeMillis() + "===";
URL url = new URL(requestURL);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true); // indicates POST method
httpConn.setDoInput(true);
httpConn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
httpConn.setRequestProperty("User-Agent", "CodeJava Agent");
httpConn.setRequestProperty("Test", "Bonjour");
outputStream = httpConn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
true);
}
public void addFormField(String name, String value) {
writer.append("--" + boundary).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name=\"" + name + "\"")
.append(LINE_FEED);
writer.append("Content-Type: text/plain; charset=" + charset).append(
LINE_FEED);
writer.append(LINE_FEED);
writer.append(value).append(LINE_FEED);
writer.flush();
}
public void addFilePart(String fieldName, File uploadFile)
throws IOException {
String fileName = uploadFile.getName();
writer.append("--" + boundary).append(LINE_FEED);
writer.append(
"Content-Disposition: form-data; name=\"" + fieldName
+ "\"; filename=\"" + fileName + "\"")
.append(LINE_FEED);
writer.append(
"Content-Type: "
+ URLConnection.guessContentTypeFromName(fileName))
.append(LINE_FEED);
writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
writer.append(LINE_FEED);
writer.flush();
FileInputStream inputStream = new FileInputStream(uploadFile);
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
inputStream.close();
writer.append(LINE_FEED);
writer.flush();
}
public void addHeaderField(String name, String value) {
writer.append(name + ": " + value).append(LINE_FEED);
writer.flush();
}
public List<String> finish() throws IOException {
List<String> response = new ArrayList<String>();
writer.append(LINE_FEED).flush();
writer.append("--" + boundary + "--").append(LINE_FEED);
writer.close();
// checks server's status code first
int status = httpConn.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
response.add(line);
}
reader.close();
httpConn.disconnect();
} else {
throw new IOException("Server returned non-OK status: " + status);
}
return response;
}
public static void main(String[] args) {
String charset = "UTF-8";
File uploadFile1 = new File(filename);
String requestURL = url;
try {
MultipartUtility multipart = new MultipartUtility(requestURL, charset);
multipart.addHeaderField("User-Agent", "CodeJava");
multipart.addHeaderField("Test-Header", "Header-Value");
multipart.addFormField("description", "Cool Pictures");
multipart.addFormField("keywords", "Java,upload,Spring");
multipart.addFilePart("fileUpload", uploadFile1);
List<String> response = multipart.finish();
System.out.println("SERVER REPLIED:");
for (String line : response) {
System.out.println(line);
}
} catch (IOException ex) {
System.err.println(ex);
}
}
}
I have an AWS lambda sample, created using AWS Toolkit for eclipse. I added a config.properties file in the project from eclipse. I am also then uploading using right click project->Amazon Web Services -> Upload
But when I test on aws console, it gives me filenotfound for config.properties.
Please help!
Here is my project structure: I get error at line 33 telling that config.properties file not found.
here is my lambda function:
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
public class LambdaFunctionHandler implements RequestHandler<String, WebConnectResponse> {
#Override
public void handleRequest(String input, Context context) {
context.getLogger().log("Input: " + input);
try {
new PreviewService().GetPreview(input);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public void GetPreview(String downloadUrl) throws Exception{
input = new FileInputStream("config.properties"); //ERROR HERE: FileNotFoundException by aws lambda when testing on aws lambda console.
props.load(input);
//Download File
downloadFileFromUrl(new URL(downloadUrl));
return null;
}
public void downloadFileFromUrl(URL downloadUrl)throws Exception{
FileUtils.copyURLToFile(downloadUrl, new File("<filepath>"));
uploadFileToServer("<filepath>");
}
public void uploadFileToServer(String filePath) throws Exception
{
String fileExternalRefId = "id";
String param = getProperty("param");
URL uploadUrl = new URL(getProperty("uploadurl"));
File contents = new File("<filepath>");
String boundary = Long.toHexString(System.currentTimeMillis());
String CRLF = "\r\n"; //Line Separator required by multipart/form-data
URLConnection connection = uploadUrl.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
connection.addRequestProperty("file_name", contents.getName());
connection.addRequestProperty("id", fileId);
try(
OutputStream output = connection.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, "UTF-8"), true);
) {
//Send headers/params
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF);
writer.append("Content-Type: application/xml; charset=UTF-8").append(CRLF);
writer.append(CRLF).append(param).append(CRLF).flush();
//Send contents
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"file-content\"; filename=\"" + contents.getName() + "\"").append(CRLF);
writer.append("Content-Type: application/xml; charset=UTF-8").append(CRLF);
writer.append(CRLF).flush();
Files.copy(contents.toPath(), output);
//IOUtils.copy(in, output);
output.flush();
writer.append(CRLF).flush();//It indicates end of boundary
writer.append("--" + boundary + "--").append(CRLF).flush();
}
int responseCode = ((HttpURLConnection) connection).getResponseCode();
if(responseCode == 200)
{
System.out.println(responseCode);
String viewUrl = props.getProperty("url")
System.out.println(viewUrl);
}
}
public String getProperty(String key)
{
return props.getProperty(key);
}
}
Here is my config.properties that looks like
key1=value1
key2=value2
I have little experience with AWS, but when you work with java Files or FileInputStreams must use the file path and you are using just the file name.
I think your code should be:
input = new FileInputStream("/[appDeployPath]/config.properties");
Maybe a better approach is to use:
getClass().getClassLoader().getResource("config.properties")
I also had config file in my project, and this is how I read the content of this file, I have answered the question here -
https://stackoverflow.com/a/42757653/5892553
I'm trying to upload my file to node.js server with javaFX
This code is for node.js server to upload my file.
Simplified my code.
var express = require('express');
var path = require('path');
var logger = require('morgan');
var methodOverride = require('method-override');
var app = express();
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var argv = require('optimist').argv;
var fs = require('fs');
app.use('/js', express.static(__dirname + '/js'));
app.use(morgan('dev'));
app.use(methodOverride());
app.use(bodyParser({keepExtensions:true,uploadDir:path.join(__dirname,'/files')}));
var busboy = require('connect-busboy');
app.use(busboy());
var fileupload = require('fileupload').createFileUpload('/home/kimmj8409/Myweb_front_end').middleware
app.post('/upload', fileupload, function(req, res) {
res.send(req.body);
})
app.listen(8080, argv.fe_ip);
console.log("App listening on port 8080");
and It is javacode to connect with this node.js server
MultipartUtility.java
public class MultipartUtility {
private final String boundary;
private static final String LINE_FEED = "\r\n";
private HttpURLConnection httpConn;
private String charset;
private OutputStream outputStream;
private PrintWriter writer;
public MultipartUtility(String requestURL, String charset)
throws IOException {
this.charset = charset;
boundary = "===" + System.currentTimeMillis() + "===";
URL url = new URL(requestURL);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
httpConn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
httpConn.setRequestProperty("User-Agent", "CodeJava Agent");
httpConn.setRequestProperty("Test", "Bonjour");
outputStream = httpConn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
true);
}
public void addFormField(String name, String value) {
writer.append("--" + boundary).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name=\"" + name + "\"")
.append(LINE_FEED);
writer.append("Content-Type: text/plain; charset=" + charset).append(
LINE_FEED);
writer.append(LINE_FEED);
writer.append(value).append(LINE_FEED);
writer.flush();
}
public void addFilePart(String fieldName, File uploadFile)
throws IOException {
String fileName = uploadFile.getName();
writer.append("--" + boundary).append(LINE_FEED);
writer.append(
"Content-Disposition: form-data; name=\"" + fieldName
+ "\"; filename=\"" + fileName + "\"")
.append(LINE_FEED);
writer.append(
"Content-Type: "
+ URLConnection.guessContentTypeFromName(fileName))
.append(LINE_FEED);
writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
writer.append(LINE_FEED);
writer.flush();
FileInputStream inputStream = new FileInputStream(uploadFile);
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
inputStream.close();
writer.append(LINE_FEED);
writer.flush();
}
public void addHeaderField(String name, String value) {
writer.append(name + ": " + value).append(LINE_FEED);
writer.flush();
}
public List<String> finish() throws IOException {
List<String> response = new ArrayList<String>();
writer.append(LINE_FEED).flush();
writer.append("--" + boundary + "--").append(LINE_FEED);
writer.close();
// checks server's status code first
int status = httpConn.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
response.add(line);
}
reader.close();
httpConn.disconnect();
} else {
throw new IOException("Server returned non-OK status: " + status);
}
return response;
}
}
Main code :
private void TCP_File_Client() throws IOException{
String url = PATH +"/upload";
String charset = "UTF-8";
String param = "value";
File textFile = new File(data_n3_PATH);
File binaryFile = new File(data_n3_PATH);
String boundary = Long.toHexString(System.currentTimeMillis());
String CRLF = "\r\n";
URLConnection connection = new URL(url).openConnection();
HttpURLConnection http = (HttpURLConnection) connection;
http.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
File uploadFile1 = new File(data_n3_PATH);
File uploadFile2 = new File(data_n3_PATH);
String requestURL = PATH +"/upload";
try {
MultipartUtility multipart = new MultipartUtility(requestURL, charset);
multipart.addHeaderField("User-Agent", "CodeJava");
multipart.addHeaderField("Test-Header", "Header-Value");
multipart.addFormField("description", "Cool Pictures");
multipart.addFormField("keywords", "Java,upload,Spring");
multipart.addFilePart("fileUpload", uploadFile1);
multipart.addFilePart("fileUpload", uploadFile2);
List<String> response = multipart.finish();
System.out.println("SERVER REPLIED:");
for (String line : response) {
System.out.println(line);
}
} catch (IOException ex) {
System.err.println(ex);
}
}
With debugging my code, I found that POST request can go to node.js server, but I can not find file.
req.files is empty and I can not find anything looks like file in req.
and I receive IOException("Server returned non-OK status: " + status); with 500 status
How can I connect these?
read https://github.com/expressjs/multer/issues/345.
You can you node.js module multer.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I want to send images from android device to my web application running on server with tomcat. please help me in writing small code for sending image to a REST web service running on Web server. Please provide me the sample code if possible. I am stuck with what method to use. Any help would be greatly appreciated. thanks in advance.
Edit: The answer for this question is as follows
while(it.hasNext()){
File file = new File((new StringBuilder()).append(Environment.getExternalStorageDirectory()).append(File.separator).append("jcms").append(File.separator).append("Customer_").append( customer.getId()).toString());
File[] listOfFiles = file.listFiles();
for(int i=0;i<listOfFiles.length;i++){
JSONObject message = new JSONObject();
File fil=listOfFiles[i];
FileInputStream imageInFile = new FileInputStream(fil);
byte imageData[] = new byte[(int)fil.length()];
imageInFile.read(imageData);
String imageDataString = encodeImage(imageData);
URL url=new URL(ClearCustomersContract.CLEAR_SERVER_URL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestMethod("POST");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(imageDataString);
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
while (in.readLine() != null) {
}
in.close();
}
}
And The REST Webservice on server side is like
#Override
#POST
#Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_OCTET_STREAM})
#Path("/getData")
public Response getAllTheSyncData(InputStream incomingData) {
StringBuilder sb = new StringBuilder();
try {
BufferedReader in = new BufferedReader(new InputStreamReader(incomingData));
String line = null;
while ((line = in.readLine()) != null) {
sb.append(line);
}
} catch (Exception e) {
System.out.println("Error Parsing: - ");
}
return Response.status(200).entity("Success").build();
}
and this is how we convert the string back to image.
byte[] imageByteArray = decodeImage(jsonObj.get("imageData").toString());
imageOutFile = new FileOutputStream(
"C:/Users/SUNILKUMAR/Desktop/result.jpg");
// Write a image byte array into file system
imageOutFile.write(imageByteArray);
imageOutFile.close();
Check the link . it gives complete example of how to upload file to server.
or check below code -
public class HttpFileUpload implements Runnable{
URL connectURL;
String responseString;
String Title;
String Description;
byte[ ] dataToServer;
FileInputStream fileInputStream = null;
HttpFileUpload(String urlString, String vTitle, String vDesc){
try{
connectURL = new URL(urlString);
Title= vTitle;
Description = vDesc;
}catch(Exception ex){
Log.i("HttpFileUpload","URL Malformatted");
}
}
void Send_Now(FileInputStream fStream){
fileInputStream = fStream;
Sending();
}
void Sending(){
String iFileName = "ovicam_temp_vid.mp4";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
String Tag="fSnd";
try
{
Log.e(Tag,"Starting Http File Sending to URL");
// Open a HTTP connection to the URL
HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"title\""+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(Title);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"description\""+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(Description);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + iFileName +"\"" + lineEnd);
dos.writeBytes(lineEnd);
Log.e(Tag,"Headers are written");
// create a buffer of maximum size
int bytesAvailable = fileInputStream.available();
int maxBufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[ ] buffer = new byte[bufferSize];
// read file and write it into form...
int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable,maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0,bufferSize);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
fileInputStream.close();
dos.flush();
Log.e(Tag,"File Sent, Response: "+String.valueOf(conn.getResponseCode()));
InputStream is = conn.getInputStream();
// retrieve the response from server
int ch;
StringBuffer b =new StringBuffer();
while( ( ch = is.read() ) != -1 ){ b.append( (char)ch ); }
String s=b.toString();
Log.i("Response",s);
dos.close();
}
catch (MalformedURLException ex)
{
Log.e(Tag, "URL error: " + ex.getMessage(), ex);
}
catch (IOException ioe)
{
Log.e(Tag, "IO error: " + ioe.getMessage(), ioe);
}
}
#Override
public void run() {
// TODO Auto-generated method stub
}
}
public void UploadFile(){
try {
// Set your file path here
FileInputStream fstrm = new FileInputStream(Environment.getExternalStorageDirectory().toString()+"/DCIM/file.mp4");
// Set your server page url (and the file title/description)
HttpFileUpload hfu = new HttpFileUpload("http://www.myurl.com/fileup.aspx", "my file title","my file description");
hfu.Send_Now(fstrm);
} catch (FileNotFoundException e) {
// Error: File not found
}
}
You can use below code to upload image with REST webservice
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext httpContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(
"YOUR WEB SERVICE URL");
entity = getMultipleEntityUpload();
httpPost.setEntity(entity);
HttpResponse httpResponse = httpClient.execute(httpPost,
httpContext);
HttpEntity httpEntity = httpResponse.getEntity();
InputStream is = httpEntity.getContent();
String line = "";
StringBuilder total = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(
is));
while ((line = rd.readLine()) != null) {
total.append(line);
}
String result =total.toString();
} catch (Exception e) {
// TODO: handle exception
}
private MultipartEntity getMultipleEntityUpload() {
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
//imagePic is bitmap of your image
imagePic.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] arrByteImage = stream.toByteArray();
try {
entity.addPart(WS_Key_Constant.KEY_IMAGE, new ByteArrayBody(
arrByteImage, ".jpg"));
} catch (Exception e) {
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return entity;
}