file upload using spring 3 - file-upload

i'm uploading an image file from this page and i'm getting nullpointer exception for multipartfile creation , i'm unable to understand where i did mistake? and i'm newbie for java
fileupload.jsp
<form modelAttribute="uploadFile" name="frm" method="post"
enctype="multipart/form-data" onSubmit="return Validate();">
<form:label for="fileData" path="fileData">File</form:label>
<input path="fileData" id="image" type="file" />
<input type="submit" value="Upload" />
</form>
UploadFile.java
its a bean page with commonsmultiparfile as class member
public class UploadFile {
private String filename;
private CommonsMultipartFile fileData;
/**
* #return the filename
*/
public String getFilename() {
return filename;
}
/**
* #param filename the filename to set
*/
public void setFilename(String filename) {
this.filename = filename;
}
/**
* #return the fileData
*/
public CommonsMultipartFile getFileData() {
return fileData;
}
/**
* #param fileData the fileData to set
*/
public void setFileData(CommonsMultipartFile fileData) {
this.fileData = fileData;
}
}
FileUploadController
#RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
public String fileupload(
serviceOrder,HttpSession session,
ModelMap model, HttpServletRequest request,UploadFile uploadFile,
HttpServletResponse response, Object command, BindingResult result) throws Exception {
if (result.hasErrors()) {
for (ObjectError error : result.getAllErrors()) {
logger.info("Error: " + error.getCode() + " - "
+ error.getDefaultMessage());
}
return "//fileUpload";
}
try{
MultipartFile multipartFile = uploadFile.getFileData();
InputStream inputStream = null;
OutputStream outputStream = null;
logger.info("---------------"+uploadFile);
logger.info("---------------------------"+multipartFile);
if (multipartFile.getSize() > 0) {
inputStream = multipartFile.getInputStream();
// File realUpload = new File("C:/");
outputStream = new FileOutputStream("D:\\Images\\"
+ multipartFile.getOriginalFilename());
logger.info("Original File Name"+multipartFile.getOriginalFilename());
int readBytes = 0;
byte[] buffer = new byte[8192];
while ((readBytes = inputStream.read(buffer, 0, 8192)) != -1) {
logger.info("writing data into file.....");
outputStream.write(buffer, 0, readBytes);
}
outputStream.close();
inputStream.close();
session.setAttribute("uploadFile", "D:\\Images\\"
+ multipartFile.getOriginalFilename());
}
} catch(Exception e) {
e.printStackTrace();
}
i'm uploading an image file from this page and i'm getting nullpointer exception for multipartfile creation , i'm unable to understand where i did mistake? and i'm newbie for java

Change your controller class method to this and give it a try
public String fileupload(HttpSession session,#ModelAttribute UploadFile uploadFile,BindingResult result){
}
I removed the HttpRequest and Response variables as they are not being used and moved the BindingResult object to be next to the ModelAttribute.
Also try to include null checks in the code before accessing the elements.

Did you define the multipartresolver bean
eg you can declare the bean in
"<"bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" /">"

Related

"multipart config was not present on Servlet" when trying to upload a file with JAX-RS class

I have the following JAX-RS class to upload a file from a browser (implemented in Wildfly 14). Problem is I get the error multipart config was not present on Servlet. Since I annotated the class with #Consumes({ MediaType.MULTIPART_FORM_DATA }) I'm not sure what is missing. How to fix this problem?
#Produces({ MediaType.APPLICATION_JSON })
#Consumes({ MediaType.MULTIPART_FORM_DATA })
public class FileUploadService {
#Context
private HttpServletRequest request;
#POST
#Path("/upload")
public Response processUpload() throws IOException, ServletException {
String path = "/mypath";
for (Part part : request.getParts()) {
String fileName = getFileName(part);
String fullPath = path + File.separator + fileName;
// delete file if exists
java.nio.file.Path path2 = FileSystems.getDefault().getPath(fullPath);
Files.deleteIfExists(path2);
// get file input stream
InputStream fileContent = part.getInputStream();
byte[] buffer = new byte[fileContent.available()];
fileContent.read(buffer);
File targetFile = new File(fullPath);
// write output file
OutputStream outStream = new FileOutputStream(targetFile);
outStream.write(buffer);
outStream.close();
}
return Response.ok("OK").build();
}
private String getFileName(Part part) {
for (String content : part.getHeader("content-disposition").split(";")) {
if (content.trim().startsWith("filename"))
return content.substring(content.indexOf("=") + 2, content.length() - 1);
}
return "";
}
}

React-Native can't use jni library correctly

I'm using nanohttpd in my native java code. When I use it normally everything looks good, but when I use jni library methods it does not work.
my app uses nanohttpd to make stream for mediaPlayer.
native methods:
public native String LH();
public native int P();
public native String EngineGS(Context context);
public native byte[] OGB(byte[] inputBuff);
variables :
private MediaPlayer mp;
private HTTPServer encryptServer;
nanohttpd class:
public class HTTPServer extends NanoHTTPD {
public HTTPServer(int port) throws IOException {
super(port);
start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);
}
#Override
public Response serve(IHTTPSession session) {
Response response = null;
try {
InputStream inputStream = new FileInputStream("/sdcard/Download/" + "encrypted.mp3");
byte[] encryptedInputByteArray = IOUtils.toByteArray(inputStream);
byte[] decryptedByteArray = OGB(encryptedInputByteArray);
inputStream = new ByteArrayInputStream(decryptedByteArray);
int totalLength = inputStream.available();
String requestRange = session.getHeaders().get("range");
if (requestRange == null) {
response = NanoHTTPD.newFixedLengthResponse(Response.Status.OK, "audio/mpeg", inputStream, totalLength);
} else {
Matcher matcher = Pattern.compile("bytes=(\\d+)-(\\d*)").matcher(requestRange);
matcher.find();
long start = 0;
try {
start = Long.parseLong(matcher.group(1));
} catch (Exception e) {
e.printStackTrace();
}
inputStream.skip(start);
long restLength = totalLength - start;
response = NanoHTTPD.newFixedLengthResponse(Response.Status.PARTIAL_CONTENT, "audio/mpeg", inputStream, restLength);
String contentRange = String.format("bytes %d-%d/%d", start, totalLength, totalLength);
response.addHeader("Content-Range", contentRange);
}
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
play method:
#ReactMethod
public void play() {
mp.getCurrentPosition();
try {
if (encryptServer == null) {
encryptServer = new HTTPServer(P());
}
Uri uri = Uri.parse(LH() + ":" + encryptServer.getListeningPort());
mp.reset();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setDataSource(getReactApplicationContext(), uri);
mp.prepare();
mp.start();
} catch (Exception e) {
e.printStackTrace();
}
}
I do not know where the problem is.
Errors:
I think the problem comes from here:
No Content Provider: http://localhost:8080

File upload in Spring boot to add in sql db

I am working on the code but stuck. It should be able to read image file from web browser and convert into blob for sql db. I am using spring boot, hibernate, sql. no js or xml. The controller and the html codes are listed below.
#Controller
#RequestMapping("imagefile")
public class ImagefileController {#RequestMapping(value = "menu", method = RequestMethod.POST)
public String imageupload(Model model, #RequestParam("id") int id, #RequestParam("uploadFile") MultipartFile uploadFile,
RedirectAttributes redirectAttributes) {
//add photo upload coding here.
String filename=uploadFile.getOriginalFilename();
String uploadFilepath=Paths.get("." + File.separator, filename).toString();;
//need to get the file into the input stream.
//byte[] bytes = uploadFile.getBytes();
//String filename1 = uploadFile.toString();
//File f = new File(filename1);
//f.getAbsolutePath();
//FileInputStream fis = new FileInputStream(f.getAbsoluteFile());
//f.getAbsolutePath();
Byte [] imagefile;
//InputStream is = new FileInputStream(new File(filename1));
//File filename = new FileInputStream(filename1.getBytes());
//String uploadFilename = uploadFile.getOriginalFilename();
//createSessionFactory().openSession();
//Session session = sessionFactory.getSessionFactory().openSession(); //getSessionFactory().getCurrentSession();
//File uploadfile = new File(uploadfile);
// Blob fileblob = Hibernate.getLobCreator(session).createBlob(filename.getBytes()); //new FileInputStream(uploadfile), file1.length()
Menu menu = menuDao.findOne(id);
model.addAttribute("title", "Add images to the menu: " + menu.getName());
System.out.println("Original Filename is:" + uploadFile.getOriginalFilename());
System.out.println("File Class is:" + uploadFile.getClass());
System.out.println("Is the File Empty?:" + uploadFile.isEmpty());
System.out.println("File size:" + uploadFile.getSize());
System.out.println("File contentType:" + uploadFile.getContentType());
//session.close();
return "Imagefile/index";
}
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org/" xmlns:form="http://www.w3.org/1999/xhtml">
<head th:replace="fragments :: head"></head>
<body class="container">
<nav th:replace="fragments :: navigation"></nav>
<h1 th:text="${title}"></h1>
<form method="post" enctype="multipart/form-data">
<input type="file" name="uploadFile" id="file" title=" " accept="image/*"/>
<p></p>
<input type="submit" value="add photo" />
</form>
</body>
</html>
-----dao------
#Repository
#Transactional
public interface MenuDao extends CrudRepository<Menu, Integer>{
}
-------entity for sql----
#Entity
public class Imagefile {
#Id
#GeneratedValue
private int id;
private String filename;
#Lob
private Blob imagecontent;
#ManyToOne
private Menu menu;
//constructor
public Imagefile(int id, String filename, Blob imagecontent) {
this.id = id;
this.filename = filename;
this.imagecontent = imagecontent;
}
public Imagefile() {}
//Getters and Setters - Accessors.
public int getId() {
return id;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public Blob getImagecontent() {
return imagecontent;
}
public void setImagecontent(Blob imagecontent) {
this.imagecontent = imagecontent;
}
public Menu getMenu() {
return menu;
}
public void setMenu(Menu menu) {
this.menu = menu;
}
}
Here is the output for the test.
Original Filename is:40 Brookside.jpg
File Class is:class org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile
Is the File Empty?:false
File size:473735
File contentType:image/jpeg
Here how I'll proceed to store the file in FileSystem and path in DB.
public String imageupload(#RequestPart("uploadFile") MultipartFile uploadFile,...) {
String FILES_FOLDER = "C:/MyFilesDirectory/";
String PHOTOS_FOLDER= "PHOTOS/";
String photoName = uploadFile !=null ? uploadFile.getOriginalFileName(): null;
String DIRECTORY = FILES_FOLDER+PHOTOS_FOLDER+photoName;
//Now we transfer the file to DIRECTORY
File file = new File(DIRECTORY);
//check if 'file' does not exist then create it
// finally :
uploadFile.transferTo(file);
//Then save 'DIRECTORY' in your db
menuDao.save(DIRECTORY); // I don't know what is inside your menuDao
}
Note that I am using #RequestPart instead of #RequestParam.
EDIT: LOADING FILE
Example of code for displaying your image. Let's suppose you have this in your view
<img src="get-image" />
Then in your handler method you will have :
#RequestMapping("get-image" )
#ResponseBody
public byte[] getImage(){
//retrieve your image from DB
//transform it to byte[]
// then return it
}

Error code 706 when signing PDF using Web Agent in Java

When testing the Web Agent sample in Java, I am getting an error reply
<?xml version="1.0" encoding="utf-8"?>
<response xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" type="error">
<Error>
<returnCode>706</returnCode>
<errorMessage>Value cannot be null.
Parameter name: s</errorMessage>
</Error>
</response>
I followed the Ruby example in the CoSign Web Agent samples and the documentation
I have used the demo.pdf file provided in the sample.
This is the XML (from test app) sent in the POST request (the <content></content> has the Base64 encoded PDF, but omitted because of length).
<?xml version="1.0" encoding="utf-8" ?>
<request>
<Logic>
<allowAdHoc>true</allowAdHoc>
<workingMode>pull</workingMode>
<enforceReason>false</enforceReason>
</Logic>
<Url>
<finishURL>http://localhost:64956/retrieveSignedFile.aspx</finishURL>
</Url>
<Document>
<fileID>1234567890</fileID>
<contentType>pdf</contentType>
<content>{BASE64 encoded pdf content}</content>
</Document>
</request>
The following is the java code I have used:
public class CoSignTest {
private static final String INPUT = "D:\\tmp\\demo.pdf";
private static final String PRECONTENT = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" +
"<request>\n" +
" <Logic>\n" +
" <allowAdHoc>true</allowAdHoc>\n" +
" <workingMode>pull</workingMode>\n" +
" <enforceReason>false</enforceReason>\n" +
" </Logic>\n" +
" <Url>\n" +
" <finishURL>http://localhost:64956/retrieveSignedFile.aspx</finishURL>\n" +
" </Url>\n" +
" <Document>\n" +
" <fileID>1234567890</fileID>\n" +
" <contentType>pdf</contentType>\n" +
" <content>";
private static final String POSTCONTENT = "</content>\n" +
" </Document>\n" +
"</request>";
private static final String POST_URL = "https://webagentdev.arx.com/Sign/UploadFileToSign";
private static final String PULL_URL = "https://webagentdev.arx.com/Sign/DownloadSignedFileG";
public static final int TIMEOUT = 300000;
public static void main(String[] args) throws Exception {
InputStream is = new FileInputStream(INPUT);
String content = PRECONTENT + new String(Base64.encodeBase64(loadResource(is)), "UTF-8") + POSTCONTENT;
System.out.println(content);
String reply = new String(sendDocForProcessing(URLEncoder.encode(content, "UTF-8")));
System.out.println(reply);
System.out.println("DONE");
}
private static String sendDocForProcessing(String content) throws Exception {
HttpClient client = null;
HttpMethodBase method = null;
SimpleHttpConnectionManager mgr = new SimpleHttpConnectionManager();
String reply = "";
try {
mgr.getParams().setConnectionTimeout(TIMEOUT);
mgr.getParams().setSoTimeout(TIMEOUT);
client = new HttpClient(mgr);
method = new PostMethod(POST_URL);
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(1, false));
method.getParams().setParameter("http.socket.timeout", TIMEOUT);
client.getHttpConnectionManager().getParams().setConnectionTimeout(TIMEOUT);
client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
method.getParams().setParameter("inputXML", content);
client.executeMethod(method);
reply = new String(method.getResponseBody());
} catch (Exception e) {
e.printStackTrace();
} finally {
if(method != null) {
method.releaseConnection();
}
client = null;
mgr.shutdown();
}
if (isSigningSuccessful(reply)) {
return reply;
} else {
throw new Exception("Failed in signing the document. Error: " + reply);
}
}
private static boolean isSigningSuccessful(String reply) throws ParserConfigurationException, IOException, SAXException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new ByteArrayInputStream(reply.getBytes()));
Element elem = doc.getDocumentElement();
String type = elem.getAttribute("type");
return !"error".equals(type);
}
public static byte[] loadResource(InputStream in) {
if (in == null) {
return new byte[0];
}
try {
int indice, tempIndice;
byte[] tempArr;
byte[] mainArr = new byte[0];
byte[] byteArr = new byte[65535];
for (indice = 0; (indice = in.read(byteArr)) > 0;) {
tempIndice = mainArr.length + indice;
tempArr = new byte[tempIndice];
System.arraycopy(mainArr, 0, tempArr, 0, mainArr.length);
System.arraycopy(byteArr, 0, tempArr, mainArr.length, indice);
mainArr = tempArr;
}
in.close();
return mainArr;
} catch (Exception e) {
e.printStackTrace();
}
return new byte[0];
}
}
The XML elements are case sensitive and must be passed as shown in the documentation (e.g. Document instead of document, Auth instead of auth and so on). In addition, your XML request is missing the finishURL parameter which is mandatory.
Also note that some parameters in your XML request are obsolete. See the updated request parameter list in the link above. A sample XML is available here.
Thanks for adding your Java code. Note that the HttpClient instance is configured incorrectly and as a result the http-post request is sent empty. Take a look at the modifications I did in your sendDocForProcessing function in order to properly post the XML content:
private static String sendDocForProcessing(String content) throws Exception {
HttpClient client = null;
PostMethod method = null;
String reply = "";
try {
client = new HttpClient();
method = new PostMethod(POST_URL);
method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
NameValuePair[] data = { new NameValuePair("inputXML", content) };
method.setRequestBody(data);
client.executeMethod(method);
reply = method.getResponseBodyAsString();
} catch (Exception e) {
e.printStackTrace();
} finally {
if(method != null) {
method.releaseConnection();
}
}
if (isSigningSuccessful(reply)) {
return reply;
} else {
throw new Exception("Failed in signing the document. Error: " + reply);
}
}
The content passed to the above function should not be URL-encoded as it is already done by the HttpClient library.
In addition, when analyzing the response, I suggest you to check the value of the returnCode element rather than the type property. The response is always of type 'error'.
Also note that the function name isSigningSuccessful is misleading as this stage is still prior to the act of signing.

Writing PDF content on response stream in openrasta

I want to render a pdf in Iframe. So if I do a GET request to http://localhost/pdf/2, it should return PDF content in the response stream. The other way can be redirecting user to full URL of the PDF file which I don't want to do.
Thanks in advance
you can use the InMemoryFile and InMemoryDownloadableFile classes.
An example:
private class AttachmentFile : InMemoryDownloadableFile
{
public AttachmentFile(byte[] file, string filename, string contenttype)
{
OpenStream().Write(file, 0, file.Length);
this.FileName = filename;
this.ContentType = new MediaType(contenttype);
}
}
private class InlineFile : InMemoryFile
{
public InlineFile(byte[] file, string filename, string contenttype)
{
OpenStream().Write(file, 0, file.Length);
this.FileName = filename;
this.ContentType = new MediaType(contenttype);
}
}
[HttpOperation(HttpMethod.GET)]
public object Get(string filename)
{
bool inline = false; //server attachments inline or as download
try
{
inline = Convert.ToBoolean(Params["INLINE"]);
}
catch { }
string contenttype = set contentttype...
byte[] attachment = read file....
if (inline)
return new InlineFile(attachment, filename, contenttype);
else return new AttachmentFile(attachment, filename, contenttype);
}
else return new OperationResult.Forbidden();
}