JSP Writing to server directory - java

So I am using resumable.js to upload files to a server.
The directory that I want to save to is something like
/dir/files/upload/
Obviously just made up, but this directory has user permissions to write to it.
I am using JSP to listen to the POST request that resumable.js makes, and writing the
.part
files to that directory.
Sample listener:
<% if(request.getMethod().equals("POST") && request.getParameter("resumableFilename") != null){
long chunkSize = StringUtils.isEmpty(request.getParameter("resumableChunkSize"))? 0:Long.parseLong(request.getParameter("resumableChunkSize"));
String fileName = request.getParameter("resumableFilename");
long totalSize = StringUtils.isEmpty(request.getParameter("resumableTotalSize"))? 0:Long.parseLong(request.getParameter("resumableTotalSize"));
String temp_dir = "/dir/files/upload/"+request.getParameter("resumableIdentifier");//Add in user_id
String dest_dir = temp_dir+fileName+".part"+request.getParameter("resumableChunkNumber");
File fDir = new File(temp_dir);
fDir.mkdirs();
if(ServletFileUpload.isMultipartContent(request)){
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(new File(temp_dir)); ServletFileUpload upload = new ServletFileUpload(factory);
List items = upload.parseRequest(request);
ArrayListIterator iter = (ArrayListIterator)items.iterator();
FileItem item = (FileItem)iter.next();
File fileWithNewDir = new File(dest_dir);
item.write(fileWithNewDir); // write file to dest_dir (fileName.part*CHUNK_NUM*)
}
}
%>
The script is hosted on
www.site.com/pubs/res.jsp
According to the JS itself for resumable, the process of uploading it gets completed, however, a new directory is not made at all. I know it's not the write permissions, so it must be something else.
Here is my call in javascript for a new resumable object
var resume = new Resumable({
target:"res.jsp",
resumableChunkSize: 1*1024*1024,
simultaneousUploads: 3,
testChunks: false,
throttleProgressCallbacks: 1
});
It seems to be hitting the jsp file, but nothing is happening.
I followed Apache's fileupload page in order to implement that listener, but maybe I went wrong at some point.
Apache's FileUpload
Resumable.js

Location of the directory matters. It has to be within the context of the WAR. You cannot write to any location outside the context of the container. If you look at the log you may be abe to see the error message which can explain this.

Related

How to convert file path to treeUri

In my application i have a regular Settings, where user can choose a video directory on his android device, and videos found in that directory will play at some point in the application. Now, when user himself is doing that via Preferences, i am opening ACTION_OPEN_DOCUMENT_TREE, and Uri returned is treeUri, that i am later using in my Video Activity with DocumentsContract.buildChildDocumentsUriUsingTree. This part is completely fine, it's working and all is OK.
However, since this application is going to be used in enterprises, i have a request, that IT department can submit an external xml file that i am completely controlling in application external directory, with all options that you as a user can set in the application itself, and if that file exists, those options need to be implemented in SharedPreferences. I got all settings to be implemented from that external xml file, apart that video directory. I was thinking that user can give regular path in the xml, like <setting key="video_folder">/sdcard/Movies</setting>, and then i parse that in the application, get treeUri from path, and save it in SharedPreferences for later use. Any ideas if this is doable, or this should have some other approach?
I've tried this method below:
public static Uri[] getSafUris (Context context, File file) {
Uri[] uri = new Uri[2];
String scheme = "content";
String authority = "com.android.externalstorage.documents";
// Separate each element of the File path
// File format: "/storage/XXXX-XXXX/sub-folder1/sub-folder2..../filename"
// (XXXX-XXXX is external removable number
String[] ele = file.getPath().split(File.separator);
// ele[0] = not used (empty)
// ele[1] = not used (storage name)
// ele[2] = storage number
// ele[3 to (n-1)] = folders
// ele[n] = file name
// Construct folders strings using SAF format
StringBuilder folders = new StringBuilder();
if (ele.length > 4) {
folders.append(ele[3]);
for (int i = 4; i < ele.length - 1; ++i) folders.append("%2F").append(ele[i]);
}
String common = ele[2] + "%3A" + folders.toString();
// Construct TREE Uri
Uri.Builder builder = new Uri.Builder();
builder.scheme(scheme);
builder.authority(authority);
builder.encodedPath("/tree/" + common);
uri[0] = builder.build();
// Construct DOCUMENT Uri
builder = new Uri.Builder();
builder.scheme(scheme);
builder.authority(authority);
if (ele.length > 4) common = common + "%2F";
builder.encodedPath("/document/" + common + file.getName());
uri[1] = builder.build();
return uri;
}
but that gives me:
Permission Denial: reading com.android.externalstorage.ExternalStorageProvider uri content://com.android.externalstorage.documents/tree/Movies%3A/document/Movies%3A/children from pid=28318, uid=10157 requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs
I had to completely rearrange logic for playing videos, to read them from regular file:// uri's, in order to bypass SAF. In short, my question was, if you don't obtain tree URI from ACTION_OPEN_DOCUMENT, ACTION_OPEN_DOCUMENT_TREE, and similar API's, is there any way possible, to obtain a permission for such tree URI. As far as i could tell, that is not possible (not even with any kind of runtime permission presented to the user). If anyone else believes that there is such a possibility, please, let me know.

upload a file via RestEasy via MultipartOutput

I'm trying to programmatically upload a file to an enpoint via RestEasyClient.
File file = new File("/Users/michele/path/file.txt");
MultipartOutput multipartOutput = new MultipartOutput();
multipartOutput.addPart(file, MediaType.APPLICATION_OCTET_STREAM_TYPE, "file.txt");
Entity<MultipartOutput> entity = Entity.entity(multipartOutput, MediaType.MULTIPART_FORM_DATA_TYPE);
//client is an instance of org.jboss.resteasy.client.jaxrs.ResteasyClient
client
.target("http://localhost:8080/endpoint")
.request()
.post(entity);
The problem is that the backend does not "find" the file that I uploaded
backend code
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload fileUpload = new ServletFileUpload(factory);
List<FileItem> items = fileUpload.parseRequest(httpReq);
items is always empt.
Using MultipartFormDataOutput::addFormData, as described in many articles, works but does not fit my use case.
Also using apache.http.client.HttpClient works, but I prefer to avoid adding dependencies to my client.
Any ideas?
Found it.
The trick was to use MultipartFormDataOutput and to set the filename when adding a part
MultipartFormDataOutput multipartOutput = new MultipartFormDataOutput();
multipartOutput.addFormData("uploaded file", file, MediaType.APPLICATION_OCTET_STREAM_TYPE, "file.txt");

Java file upload using Oreilly Multipartrequest

I'm doing a java web application that manage online auctions. At a certain point in the application the user can sell a product, so I have built a page where there is a form; in this form I have to handle the file upload using Oreilly Multipartrequest library. When I click the submit button a servlet should handle all the parameters, add the product on the database, and then redirect to the users page, but instead of doing it, the application hangs in a blank page. I'm using netbeans so I have checked the logs, but I can't find any errors; I have also checked on the logs inside the tomcat folder, but again I can't any errors. I don't know what to do neither where to search the solution.
Here is the part of the code that handle the upload:
try {
MultipartRequest multi =
new MultipartRequest(request, getServletContext().getRealPath("/img"), 10*1024*1024,
"ISO-8859-1", new DefaultFileRenamePolicy());
Enumeration files = multi.getFileNames();
while (files.hasMoreElements()) {
name = (String)files.nextElement();
filename = multi.getFilesystemName(name);
// String originalFilename = multi.getOriginalFileName(name);
// String type = multi.getContentType(name);
File f = multi.getFile(name);
if (f != null) {
session.setAttribute("success", "file written correctly");
}
}
} catch (IOException IEx) {
this.getServletContext().log("Error reading saving file");
}
Am I doing something wrong, or my idea is correct?
P.S. If the user decide not to upload any picture, I have to put on the database a default picture.

how to save large files inside the data base.?

I am using JSP form to upload and Servlet to store a large-sized file in a MySQL database. and because i am new to Java in general, i need a really urgent help.
I tried to store the file in a String value but i got error that string index is out of boundary.
I have the database table Files which has (varchar File_Name, Blob File_data, Varchar File_Date) .
And i need to store the uploaded file inside the
I had this code in servlet:
** BTW : i have no idea why "DiskFileUpload, parseRequest " have strikethrough line ?
try {
InputStream uploadedFile = null;
<strike>DiskFileUpload</strike> fu = new </strike>DiskFileUpload</strike>();
// If file size exceeds, a FileUploadException will be thrown
fu.setSizeMax(10000000);
List fileItems = fu.<strike>parseRequest</strike>(request);
Iterator itr = fileItems.iterator();
while (itr.hasNext()) {
FileItem fi = (FileItem) itr.next();
//Check if not form field so as to only handle the file inputs
//else condition handles the submit button input
if (!fi.isFormField()) { // If the form fiel is a file
uploadedFile = fi.getInputStream();
}
What type of data should I convert uploadFile cvariable to be able to store it in a Blob attribute ?
Strike through means API is deprecated and those classes/methods may not work as expected.
Storing file to database, you need to store the content as bytes in blob filed. See this discussion. Even though it is related to some error, OP posted code on how to do this.

multipart/form-data not working with servlets

I am not really sure why the html form with the tag enctype="multipart/form-data" does not pass the objects it should pass. this is the case with mozilla and firefox.
for IEs case, for example, I use html control to choose a file, it does get what it is supposed to get.
Now I just want to know if there are any alternatives I can use to pass in files through http request object because the enctype="multipart/form-data" seems to be having some compatibility issues but I am not really sure
any suggestions would be appreciated! :D
First of all, you have to provide a little bit of code to show what you have done, and to know what went wrong. Anyway, I am assuming that you have to upload a file to the server using HTML file upload control.
File upload or to say multipart/form-data encoding type support is not implemented in HttpServlet implementation. So, the request.getParameter() don't work with multipart/form-data. You have to use additional libraries which provide support for this. Apache Commons File Upload is a good example. Their using fileupload guide will help you to get started with the library. Here is a simple example (compiled from using file upload guide).
// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Parse the request
List /* FileItem */ items = upload.parseRequest(request);
// Process the uploaded items
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
// Process form field.
String name = item.getFieldName();
String value = item.getString();
} else {
// Process uploaded file.
String fieldName = item.getFieldName();
String fileName = item.getName();
String contentType = item.getContentType();
boolean isInMemory = item.isInMemory();
long sizeInBytes = item.getSize();
if (writeToFile) {
File uploadedFile = new File("path/filename.txt");
item.write(uploadedFile);
}
}
}
} else {
// Normal request. request.getParameter will suffice.
}
got it. if someone else might have a problem like this, this was my problem. i checked the content type of the file for me to ensure that the objects passed is of a certain type. in IE, it returns application/x-zip-compressed THAT IS ONLY FOR IE but mozilla and chrome seems to be returning a different content type for the zip file which is application/octet-stream.
so i just added the application/octet-stream to the valid filetypes and it seems to be working now

Categories