Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can i upload file from Android using (asmx) .net WebService
    primarykey
    data
    text
    <p>i have browse the file on mobile and upload to server</p> <p><strong>I have Issue in File Upload its give me File Not Found.</strong></p> <p><strong>.Net File Upload method (Server Side Code)</strong></p> <pre><code>Public Function UploadFiles(ByVal docs As Byte(), ByVal filename As String, ByVal UserId As Integer, ByVal PartnerId As Integer, ByVal IdeaId As Integer) As String 'Public Function UploadFiles(ByVal doctitle As String, ByVal docdescription As String, ByVal docs As Byte(), ByVal filename As String, ByVal UserId As Integer, ByVal UserType As String, ByVal IdeaId As Integer, ByVal PartnerId As Integer) As String Dim NoOfDocs As Integer Dim iCount As Integer Dim sConId As String Dim sConId1 As String Dim sConId2 As String Dim txtTitle As eCMSLib.Component.TextBox Dim txtDesc As eCMSLib.Component.TextBox Dim Upload1 As FileStream Dim dirname As String Dim strDocTitle As String = "" Dim strDocDesc As String = "" Dim dirconsultee As String Dim createdirconsultee As String Dim ServerPath As String Dim ServerPath1 As String Dim strFilename As String Dim strOnlyFilename As String = "" Dim objDoc As New Elegant.BusinessLogicLayer.DocumentAndResponse Dim objIdea As New Ideas Dim createdir As String NoOfDocs = GetNumberOfUploadDocs(PartnerId) Try '--------------------------------------------------------------------------- 'Create consultation directory dirname = "Idea" &amp; IdeaId createdir = Server.MapPath("uploaddocs") Dim dir As DirectoryInfo Dim tempdir As String tempdir = createdir &amp; "\" &amp; dirname dir = New DirectoryInfo(tempdir) If dir.Exists = True Then Else dir.Create() End If '--------------------------------------------------------------------------- 'Create the consultee directory dirconsultee = "Consultee" &amp; UserId 'UserID = Integer.Parse(Session("UID_User")) createdirconsultee = Server.MapPath("../uploaddocs/Idea" &amp; IdeaId &amp; "") Dim dirconsultee1 As DirectoryInfo Dim tempdir1 As String tempdir1 = createdirconsultee &amp; "\" &amp; dirconsultee dirconsultee1 = New DirectoryInfo(tempdir1) If dirconsultee1.Exists = True Then Else dirconsultee1.Create() End If '--------------------------------------------------------------------------- NoOfDocs = 1 For iCount = 0 To NoOfDocs - 1 ServerPath = "" ServerPath = Server.MapPath("../uploaddocs/" &amp; dirname &amp; "/" &amp; dirconsultee &amp; "") ServerPath1 = dirname &amp; "/" &amp; dirconsultee Directory.SetCurrentDirectory(ServerPath) sConId = "m_txt_" &amp; iCount &amp; "_" &amp; "UF" &amp; iCount 'sConId1 = doctitle(iCount) 'sConId2 = docdescription(iCount) 'sConId1 = doctitle 'sConId2 = docdescription Dim ms As New MemoryStream(docs) 'Dim fs As New System.IO.FileStream(dirname &amp; "/" &amp; dirconsultee &amp; "/" &amp; sConId, IO.FileMode.Create, System.IO.FileAccess.ReadWrite) 'ms.WriteTo(fs) 'ms.Close() 'fs.Close() 'fs.Dispose() 'Upload1 = fs 'txtTitle = CType(tbluploaddoc.FindControl(sConId1), eCMSLib.Component.TextBox) 'txtDesc = CType(tbluploaddoc.FindControl(sConId2), eCMSLib.Component.TextBox) Dim fs As System.IO.FileStream 'If sConId1 &lt;&gt; "" Then ' strDocTitle = sConId1 'Else ' strDocTitle = "" 'End If 'If sConId2 &lt;&gt; "" Then ' strDocDesc = sConId2 'Else ' strDocDesc = "" 'End If If docs IsNot Nothing Then 'If FileFieldSelected(Upload1) = True Then strFilename = sConId If strFilename &lt;&gt; String.Empty Then strOnlyFilename = System.IO.Path.GetFileName(strFilename) If Not eCMSLib.Common.Operation.CommonFunctions.isValidUserDefineFile(strOnlyFilename, ".doc,.docx,.pdf,.ppt,.pptx,.pps,.gif,.jpeg,.jpg,.bmp,.htm,.html") Then 'lblErroMsg.Visible = True Dim strErroMsg As String = "Invalid File format. You can upload only files with.doc,.docx,.pdf,.ppt,.pptx,.pps,.gif,.jpeg,.jpg,.bmp,.htm,.html extesion." 'Return lblErroMsg.Text 'Return False Context.Response.Write("{""Uploaddocs"":" &amp; New JavaScriptSerializer().Serialize(strErroMsg) &amp; "}") End If ServerPath = ServerPath &amp; "/" &amp; strOnlyFilename ServerPath1 = dirname &amp; "/" &amp; dirconsultee &amp; "/" &amp; strOnlyFilename 'If Upload1.PostedFile.ContentLength &gt; 15000000 Then ' 'lblErroMsg.Visible = True ' Dim strErroMsg As String = "File size is too large. Please try again." ' Context.Response.Write("{""Uploaddocs"":" &amp; New JavaScriptSerializer().Serialize(strErroMsg) &amp; "}") ' 'Return lblErroMsg.Text ' 'Exit Function 'End If Dim bln As Boolean bln = objDoc.IsFileExist(ServerPath1, UserId) If bln = True Then 'lblErroMsg.Visible = True Dim strErroMsg As String = "This file " &amp; strOnlyFilename &amp; "has already been uploaded." Context.Response.Write("{""Uploaddocs"":" &amp; New JavaScriptSerializer().Serialize(strErroMsg) &amp; "}") ' Return lblErroMsg.Text 'Exit Function End If '-------------------------------------------------------------------------------------- Dim BLNUpload As Boolean = ValidationForUpload(UserId, IdeaId) If BLNUpload = False Then Dim UploadedFile As Integer Dim objDocs1 As New DocumentAndResponse UploadedFile = objDocs1.CountUplodedFileForIdeaUser(UserId, IdeaId) 'Dim strErroMsg As String = "Your documents " &amp; UploadedFile &amp; " have been uploaded ." 'Return lblErroMsg.Text 'Exit Function End If '-------------------------------------------------------------------------------------- 'eCMSLib.Common.Operation.CommonFunctions.UploadFile(Upload1, ServerPath, 15000000) fs = New System.IO.FileStream(dirname &amp; "/" &amp; dirconsultee &amp; "/" &amp; sConId, IO.FileMode.Create, System.IO.FileAccess.ReadWrite) ms.WriteTo(fs) ms.Close() fs.Close() fs.Dispose() End If '------------------------------------------------------------------------------------------- 'Insert Data in database for upload documents track. Dim sPath As String Dim DocRefNumber As String Dim UploadFileContForUser As Integer Dim objDocs2 As New DocumentAndResponse UploadFileContForUser = objDocs2.CountUplodedFileForIdeaUser(UserId, IdeaId) If iCount = 0 Then DocRefNumber = IdeaId &amp; "-" &amp; UserId &amp; "-" &amp; Date.Now.Day &amp; "-" &amp; Date.Now.Month &amp; "-" &amp; Date.Now.Year &amp; "-" &amp; UploadFileContForUser + iCount + 1 Else DocRefNumber = IdeaId &amp; "-" &amp; UserId &amp; "-" &amp; Date.Now.Day &amp; "-" &amp; Date.Now.Month &amp; "-" &amp; Date.Now.Year &amp; "-" &amp; UploadFileContForUser + 1 End If sPath = dirname &amp; "/" &amp; dirconsultee &amp; "/" &amp; strOnlyFilename Dim oInfo As Hashtable = New Hashtable oInfo.Add("n_fkIdeaId", IdeaId) oInfo.Add("t_DocPath", sPath) oInfo.Add("n_UplodedTime", "getdate()") oInfo.Add("n_fkUserID", UserId) oInfo.Add("t_UserType", "Consultee") oInfo.Add("t_DocType", System.IO.Path.GetExtension(strOnlyFilename)) oInfo.Add("t_DocSize", fs.Length) oInfo.Add("t_DocRefNumber", DocRefNumber) oInfo.Add("t_DocTitle", strDocTitle) oInfo.Add("t_DocDesc", strDocDesc) objDoc.AddIdeaDocument(oInfo) '------------------------------------------------------------------------------------------- 'End If End If Next Catch ex As Exception ''Throw ex objIdea.DeleteIdea(IdeaId, PartnerId) 'Added by Pinki to resolve the issue when file is invalid - (28 apr 2011) End Try Return String.Empty End Function Public Function GetNumberOfUploadDocs(ByVal PartnerID As Integer) As Integer Dim str As String Dim Number As Integer str = "SELECT ISNULL(paravaluedtl,'0') paravaluedtl from tblparameterdtl where fkparameterid='NoOFUpload_SubmittingIdea' and fkConsultPartnerID= " &amp; PartnerID &amp; " " Number = eCMSLib.Common.Operation.DatabaseIntraction.GetSingleRowColumnValue(str) Return Number End Function Public Function GetAllowUploadIdeaDocs(ByVal PartnerID As Integer) As String Dim str As String Dim strAllow As String str = "SELECT paravaluedtl from tblparameterdtl where fkparameterid='EnableUpload_SubmittingIdea' and fkConsultPartnerID= " &amp; PartnerID &amp; " " strAllow = eCMSLib.Common.Operation.DatabaseIntraction.GetSingleRowColumnValue(str) Return strAllow End Function Public Function FileFieldSelected(ByVal FileField As System.Web.UI.HtmlControls.HtmlInputFile) As Boolean ' Returns a True if the passed ' FileField has had a user post a file If FileField.PostedFile Is Nothing Then Return False If FileField.PostedFile.ContentLength = 0 Then Return False Return True End Function Public Function ValidationForUpload(ByVal UserID As Integer, ByVal IdeaID As Integer) As Boolean Dim objUserDoc As New DocumentAndResponse Dim bln As Boolean bln = objUserDoc.GetFileUploadCountForIdeaUser(UserID, IdeaID, Session("ConsultPartner")) Return bln End Function </code></pre> <p><strong>Upload Android method</strong></p> <pre><code> /** android File upload start */ public static String doFileUpload(String path, String URL) { final DataOutputStream dos; String exiting_file_path = path; Log.d("d file path---&gt;", "" + path); String boundary = "*****"; String twohypens = "--"; String lineend = "\r\n"; int maxBufferSize = 1 * 1024 * 1024; int buferSize; int bytesRead; String url_string = URL; try { Log.d("Debug", "Start Uploading"); FileInputStream fileInStream = new FileInputStream( exiting_file_path); URL url = new URL(url_string); httpUrlConn = (HttpURLConnection) url.openConnection(); httpUrlConn.setDoInput(true); httpUrlConn.setDoOutput(true); httpUrlConn.setUseCaches(false); httpUrlConn.setRequestMethod("POST"); httpUrlConn.setRequestProperty("connection", "Keep-Alive"); httpUrlConn.setRequestProperty("content-type", "multipart/form-data;boundary=" + boundary); httpUrlConn.setRequestProperty("UserId", "" + SoapParsar.UserID); httpUrlConn.setRequestProperty("PartnerId", "" + SoapParsar.PartnerID); httpUrlConn.setRequestProperty("IdeaId", "" + 1400); httpUrlConn.setRequestProperty("Path", "file://" + path); dos = new DataOutputStream(httpUrlConn.getOutputStream()); dos.writeBytes(twohypens + boundary + lineend); dos.writeBytes("content-disposition:form-data; name=\"upload_file\"; filename=\"" + exiting_file_path + "\"" + lineend); dos.writeBytes(lineend); int buferAvailable = fileInStream.available(); buferSize = Math.min(buferAvailable, maxBufferSize); final byte[] buffer = new byte[buferSize]; bytesRead = fileInStream.read(buffer, 0, buferSize); // ------------------- if (isFromCamera) { ByteArrayOutputStream stream = new ByteArrayOutputStream(); Log.d("bit map hight", "---&gt;" + resizedBitmap.getHeight()); Log.d("bit map width", "---&gt;" + resizedBitmap.getWidth()); resizedBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); byte[] byteArray = stream.toByteArray(); dos.write(byteArray, 0, byteArray.length); } else { while (bytesRead &gt; 0) { dos.write(buffer, 0, buferSize); buferAvailable = fileInStream.available(); buferSize = Math.min(buferAvailable, maxBufferSize); bytesRead = fileInStream.read(buffer, 0, buferSize); } } // --------------- dos.writeBytes(lineend); dos.writeBytes(twohypens + boundary + twohypens + lineend); fileInStream.close(); dos.flush(); dos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { DataInputStream inStream = new DataInputStream( httpUrlConn.getInputStream()); STR1 = inStream.readLine(); while ((STRRRR = inStream.readLine()) != null) { Log.d("Debug", "Server Response " + STRRRR); } inStream.close(); } catch (IOException e) { e.printStackTrace(); } /** in STRRRR you get name of photo */ Log.d("File Uploded---&gt;", "" + STR1); return STR1; } </code></pre> <p>Button Upload click code</p> <pre><code> btnPost.setOnClickListener(new OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub String title = ni_title.getText().toString(); String detail = ni_detail.getText().toString(); String tag = ni_tag.getText().toString(); String directorate = ni_directorate.getText().toString(); String filepath = ni_filepath.getText().toString(); Log.d("local file path", "" + path + "/" + filepath); boolean post_idea = true; if (title.equalsIgnoreCase("")) { ni_title.setError("Enter Title"); post_idea = false; } if (detail.equalsIgnoreCase("")) { ni_detail.setError("Enter Descrebtion"); post_idea = false; } if (tag.equalsIgnoreCase("")) { ni_tag.setError("Enter Tag"); post_idea = false; } if (directorate.equalsIgnoreCase("")) { ni_directorate.setError("Enter Directorate"); post_idea = false; } // if(filepath.equalsIgnoreCase("")){ // ni_filepath.setError("select file"); // } if (!Select_c) { Toast.makeText(add_new_idea.this, "Select Category", Toast.LENGTH_SHORT).show(); post_idea = false; } if (post_idea) { try { General_class.arrayPost.clear(); General_class.arrayPost.add(new BasicNameValuePair( "IdeaId", "0")); General_class.arrayPost.add(new BasicNameValuePair( "ideaTitle", "" + title)); General_class.arrayPost.add(new BasicNameValuePair( "ideadescription", "" + detail)); General_class.arrayPost.add(new BasicNameValuePair( "SessionId", "0")); General_class.arrayPost.add(new BasicNameValuePair( "UserID", "" + SoapParsar.UserID)); General_class.arrayPost.add(new BasicNameValuePair( "UserType", "" + SoapParsar.Usertype)); General_class.arrayPost.add(new BasicNameValuePair( "emailid", "dhaval@elegantmicroweb.com")); General_class.arrayPost.add(new BasicNameValuePair( "PartnerID", "" + SoapParsar.PartnerID)); General_class.arrayPost.add(new BasicNameValuePair( "tags", "" + tag)); General_class.arrayPost.add(new BasicNameValuePair( "categoryids", "" + selected)); /* * General_class.arrayPost.add(new BasicNameValuePair( * "categoryids", "" + selected)); */ // ni_filepath String para = "?IdeaId=0&amp;ideaTitle=" + title + "&amp;ideadescription=" + detail + "&amp;SessionId=0&amp;UserID=" + SoapParsar.UserID + "&amp;emailid=&amp;UserType=" + SoapParsar.Usertype + "&amp;PartnerID=" + SoapParsar.PartnerID + "&amp;tags=" + tag + "&amp;categoryids=" + selected; // String Res = General_class // .Call_Http_URL_PostMethod(SoapParsar.BASEURL_LOGIN // + "/AddEditIdea"); String URL = SoapParsar.BASEURL_LOGIN + "/AddEditIdea" + para; URL = General_class.replaceSpace(URL); Log.e("URL---&gt;", "" + URL); String Res = General_class.GETMethod(URL); Log.e("post idea--&gt;", "" + Res); /* * General_class.doFileUpload(ni_filepath.getText() * .toString(), SoapParsar.BASEURL_LOGIN + * "/UploadFiles"); */ /* General_class.doFileUpload("" + path + "/" +ni_filepath.getText().toString(), SoapParsar.BASEURL_LOGIN + "/UploadFiles"); */ } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } General_class.doFileUpload(path + "/" + ni_filepath.getText().toString(), SoapParsar.BASEURL_LOGIN + "/UploadFiles?UserId=" + SoapParsar.UserID + "&amp;PartnerId=" + SoapParsar.PartnerID + "&amp;IdeaId=0&amp;filename=" +ni_filepath.getText().toString()); Log.e("path----&gt;111--&gt;", "" + path); /* General_class.doFileUpload("" + path + "/" +ni_filepath.getText().toString(), SoapParsar.BASEURL_LOGIN + "/UploadFiles");*/ // General_class.doFileUpload(path + "/"+ // ni_filepath.getText().toString(),SoapParsar.BASEURL_LOGIN // + "?op=UploadFiles"); } else { Toast.makeText(add_new_idea.this, "enter all details", Toast.LENGTH_SHORT).show(); } } }); </code></pre> <p>Error Log:</p> <pre><code>URL---&gt;(21331): http://10.0.0.230:81/samplewebservice/webservice.asmx/AddEditIdea?IdeaId=0&amp;ideaTitle=kihgtff&amp;ideadescription=bhhhjhhb&amp;SessionId=0&amp;UserID=430&amp;emailid=&amp;UserType=Consultee&amp;PartnerID=9&amp;tags=%20&amp;categoryids=17 04-01 18:07:38.476: D/d file path---&gt;(21331): /mnt/sdcard/Aaa.JPG 04-01 18:07:38.476: D/Debug(21331): Start Uploading 04-01 18:07:38.726: W/System.err(21331): java.io.FileNotFoundException: `http://10.0.0.230:81/samplewebservice/webservice.asmx/UploadFiles?UserId=430&amp;PartnerId=9&amp;IdeaId=0&amp;filename=Aaa.JPG` 04-01 18:07:38.750: W/System.err(21331): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:521) 04-01 18:07:38.750: W/System.err(21331): at com.idea_mobile.General_class.doFileUpload(General_class.java:640) 04-01 18:07:38.750: W/System.err(21331): at com.idea_mobile.add_new_idea$2.onClick(add_new_idea.java:238) 04-01 18:07:38.750: W/System.err(21331): at android.view.View.performClick(View.java:2485) 04-01 18:07:38.750: W/System.err(21331): at android.view.View$PerformClick.run(View.java:9080) 04-01 18:07:38.750: W/System.err(21331): at android.os.Handler.handleCallback(Handler.java:587) 04-01 18:07:38.750: W/System.err(21331): at android.os.Handler.dispatchMessage(Handler.java:92) 04-01 18:07:38.750: W/System.err(21331): at android.os.Looper.loop(Looper.java:130) 04-01 18:07:38.750: W/System.err(21331): at android.app.ActivityThread.main(ActivityThread.java:3687) 04-01 18:07:38.750: W/System.err(21331): at java.lang.reflect.Method.invokeNative(Native Method) 04-01 18:07:38.750: W/System.err(21331): at java.lang.reflect.Method.invoke(Method.java:507) 04-01 18:07:38.750: W/System.err(21331): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867) 04-01 18:07:38.750: W/System.err(21331): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625) 04-01 18:07:38.750: W/System.err(21331): at dalvik.system.NativeStart.main(Native Method) 04-01 18:07:38.750: D/File Uploded---&gt;(21331): null 04-01 18:07:38.750: E/path----&gt;111--&gt;(21331): /mnt/sdcard </code></pre> <p>Its give me File not fount at this line:</p> <pre><code>DataInputStream inStream = new DataInputStream( httpUrlConn.getInputStream()); </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload