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
Related
I have a problem calling a webAPI in Java. Basically, I have to upload a file (xml or pdf) but I cannot get it work. I tried in Postman and it works, I had to put in the body the filename and the content of the file
If I declare the filedata as file (see pic. 3) it works. I tried to do it in Java but I cannot find a way to do it. I tried many snippets from the web buut at best when I run them I get error 500.
The code I got so far is
package api_post;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
public class API_POST {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
String charset = "UTF-8";
File uploadFile1 = new File("[fileWithPath]");
String requestURL = "";
requestURL = "[URL]";
try {
MultipartUtility multipart = new MultipartUtility(requestURL, charset);
multipart.addFormField("username", "[user]");
multipart.addFormField("password", "[pwd]");
multipart.addFormField("owner", "[owner]");
multipart.addFormField("destination", "[destination]");
multipart.addFilePart("fileData", 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);
}
}
public static 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);
outputStream = httpConn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
true);
}
/**
* Adds a form field to the request
* #param name field name
* #param value field value
*/
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();
}
/**
* Adds a upload file section to the request
* #param fieldName name attribute in <input type="file" name="..." />
* #param uploadFile a File to be uploaded
* #throws IOException
*/
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();
}
/**
* Adds a header field to the request.
* #param name - name of the header field
* #param value - value of the header field
*/
public void addHeaderField(String name, String value) {
writer.append(name + ": " + value).append(LINE_FEED);
writer.flush();
}
/**
* Completes the request and receives response from the server.
* #return a list of Strings as response in case the server returned
* status OK, otherwise an exception is thrown.
* #throws IOException
*/
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) {
System.out.println("Entrato");
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;
}}}
Can anybody help me please?
I just discovered that in postman I can see the java source code of the call. I used that and now it works.
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 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.
I hope someone can help me out.
I want to send a url as a string to the client endpoint function and then I want the endpoint function to download the image and send it then via a HTTP Post request to my servlet (also running on GAE).
The problem is - there is no image posted at all.
It's strange because if I use the exact same code (the HttpPost class) on an android client, it works fine - the image gets posted to the servlet and the servlet stores the image into the datastore / blobstore.
Isn't it possible to send a HTTP Post request from a client endpoint function to a servlet?
Solved, see answer below!
Android:
BackendApi.anyMethod("url-to-any-image").execute();
Client Endpoint Function:
#ApiMethod(path = "anyMethod")
public void anyMethod(#Named("url") String url) {
// --------------------------------------------------
// No input validation here - just a proof of concept
// --------------------------------------------------
try {
// Download image
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
Resources.asByteSource(new URL(url)).copyTo(buffer);
// Upload image
HttpPost httpPost = new HttpPost();
httpPost.setTarget(new URL(BlobstoreServiceFactory.getBlobstoreService().createUploadUrl("/upload")));
httpPost.add("image", buffer.toByteArray());
httpPost.send();
} catch (IOException e) {
LOG.log(Level.WARNING, e.getMessage(), e);
}
}
HttpPost Class:
public class HttpPost {
private final static String CRLF = "\r\n";
private String boundary;
private URL url;
private ByteArrayOutputStream buffer;
public HttpPost() {
// Generate random boundary
// Boundary length: max. 70 characters (not counting the two leading hyphens)
byte[] random = new byte[40];
new Random().nextBytes(random);
boundary = Base64.encodeBase64String(random);
// Init buffer
buffer = new ByteArrayOutputStream();
}
public void setTarget(URL url) {
this.url = url;
}
public void add(String key, String value) throws IOException {
addToBuffer("--" + boundary + CRLF);
addToBuffer("Content-Disposition: form-data; name=\"" + key + "\"" + CRLF);
addToBuffer("Content-Type: text/plain; charset=UTF-8" + CRLF + CRLF);
addToBuffer(value + CRLF);
}
public void add(String key, byte[] fileBytes) throws IOException {
addToBuffer("--" + boundary + CRLF);
addToBuffer("Content-Disposition: form-data; name=\"" + key + "\"; filename=\"" + key + "\"" + CRLF);
addToBuffer("Content-Type: application/octet-stream" + CRLF);
addToBuffer("Content-Transfer-Encoding: binary" + CRLF + CRLF);
addToBuffer(fileBytes);
addToBuffer(CRLF);
}
public void send() throws IOException {
// Add boundary end
addToBuffer("--" + boundary + "--" + CRLF);
// Open url connection
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
connection.setRequestProperty("User-Agent", "Google App Engine");
// Open data output stream
DataOutputStream request = new DataOutputStream(connection.getOutputStream());
request.write(buffer.toByteArray());
request.flush();
request.close();
// Close connection
connection.disconnect();
}
private void addToBuffer(String string) throws IOException {
buffer.write(string.getBytes());
}
private void addToBuffer(byte[] bytes) throws IOException {
buffer.write(bytes);
}
}
Http Servlet:
public class Upload extends HttpServlet {
private static final Logger LOG = Logger.getLogger(Upload.class.getName());
private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
Map<String, List<BlobKey>> blobs = blobstoreService.getUploads(request);
List<BlobKey> blobKeys = blobs.get("image");
if (blobKeys == null) {
LOG.warning("No blobkeys found");
return;
}
// Get blob key
BlobKey blobKey = blobKeys.get(0);
if (blobKey == null) {
LOG.warning("No blobkey found");
return;
}
// Create new image object
Image image = new Image();
image.setBlobKey(blobKey);
image.setTimestamp(new Date());
// Save image to datastore
OfyService.ofy().save().entity(image).now();
LOG.log(Level.INFO, "Image upload successful");
}
}
Accordingly to the Google App Engine Docs you are not allowed to fetch your own URL:
To prevent an app from causing an endless recursion of requests, a request handler is not allowed to fetch its own URL. It is still possible to cause an endless recursion with other means, so exercise caution if your app can be made to fetch requests for URLs supplied by the user.
That means the only way of doing this is to download the image on the Android client and then post it to the HttpServlet.
Android:
try {
// Download image to the Android client
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
Resources.asByteSource(new URL(url)).copyTo(buffer);
// Upload image to HttpServlet
HttpPost httpPost = new HttpPost();
httpPost.setTarget(new URL("http-servlet-upload-url"));
httpPost.add("image", buffer.toByteArray());
httpPost.send();
} catch (IOException e) {
Logcat.error(e.getMessage());
}
I am using this tutorial to upload large files but it is unable to upload even 300KB of file. Also it does not upload anything other than *.txt or *.log files. Need pointers which can help me upload large files irrespective of filetypes.
Sharing modified code
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() //<- Exception coming in this line java.io.IOException: Error writing to server
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
}
static main(args) {
String charset = "UTF-8";
File uploadFile1 = new File("C:\\1392943434245.xml");
String requestURL = "http://localhost:10060/testme";
try {
MultipartUtility multipart = new MultipartUtility(requestURL, charset);
multipart.addFilePart("fileUpload", uploadFile1);
List<String> response = multipart.finish();
println("SERVER REPLIED:");
for (String line : response) {
System.out.println(line);
}
} catch (IOException ex) {
System.err.println(ex);
}
}
}
Have you checked that your HTTP server does not impose a size limit on requests ?
Is there enough memory and disk size ?
Maybe the cause is not in your code.
Try this code, you can be able to upload any file type
public class TryFile {
public static void main(String[] ar) throws HttpException, IOException, URISyntaxException {
// TODO Auto-generated method stub
TryFile t=new TryFile();
t.method();
}
public void method() throws HttpException, IOException, URISyntaxException
{
String url="<your url>";
String fileName="<your file name>";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
FileBody fileContent= new FileBody(new File(fileName));
StringBody comment = new StringBody("Filename: " + fileName);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("file", fileContent);
httppost.setEntity(reqEntity);
System.out.println("post length"+reqEntity.getContentLength());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println("end"+resEntity.getContentLength());
}
}
This is a working code for file upload:
<jsp:useBean id="upBean" scope="session" class="javazoom.upload.UploadBean" >
<jsp:setProperty name="upBean" property="filesizelimit" value="<%= 1024 * 1024%>" />
</jsp:useBean>
try this,
try {
if (MultipartFormDataRequest.isMultipartFormData(request)) {
MultipartFormDataRequest mrequest = new MultipartFormDataRequest(request);
Hashtable files = mrequest.getFiles();
byte data[] = null;
if ((files != null) && (!files.isEmpty())) {
fileObj = (UploadFile) files.get("fileUpload");
m_imagename = fileObj.getFileName().trim();
//File type validator
if (!Utility.isValiedFileName1(m_imagename)) {
ERROR = "Invalid File Type";
response.sendRedirect("XXX.jsp");//response page
return;
}
//file uploader method call
if ((fileObj != null) && (fileObj.getFileName() != null)) {
data = fileObj.getData();
//Java method for uploading
result = imageUpload.copyImage(data);//depCode
}
}
}
} catch (Exception e) {
SystemMessage.getInstance().writeMessage(" ERROR : " + e);
}
This is part related to HTTP.
Refer
here
We can upload any number of files of any sizes using plupload.